问题描述
我需要创建一个自定义事件,它将一些数据传递给事件侦听器.我已经创建了一个如下图
I need to create a Custom Event which will pass some data to the event listener. I already created one like below
自定义事件
var event = new CustomEvent('store', { 'detail': obj });
document.getElementById("Widget").dispatchEvent(event);
听众
document.getElementById("Widget").addEventListener('store', function (e) {
console.log(e.detail);
document.getElementById("result").innerHTML = e.detail.name+"<br>"+e.detail.address;
}, false);
它在 Chrome 和 Firefox 等浏览器中运行良好,但在 IE11 中不起作用.我在 IE 中遇到错误:
It is working fine in browsers such as Chrome and Firefox but not working in IE11. I am getting an error in IE:
对象不支持此操作
CustomEvent 在 IE 中不起作用.
CustomEvent is not working in IE.
我怎样才能使这个跨浏览器兼容?我不想使用 jQuery trigger()
因为 Listener
可能不在具有 jQuery 的页面中
How can I make this cross-browser compatible ? I don't want to use jQuery trigger()
because the Listener
might not be in a page having jQuery
推荐答案
CoustomEvent 构造函数在 IE11 中不受支持.您可以使用以下pollyfill
CoustomEvent constructor is not supported in IE11.you can use following pollyfill
(function () {
if ( typeof window.CustomEvent === "function" ) return false;
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
复制自 MDN
这篇关于跨浏览器兼容的自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!