【问题标题】:CustomEvent() constructor is not supportive in IEIE 不支持 CustomEvent() 构造函数
【发布时间】:2018-06-07 17:54:38
【问题描述】:

IE 不支持CustomEvent() 构造函数。是否有可能使其至少与 IE11 兼容?它适用于 Chrome 和 Firefox 等其他浏览器。

例如:-

var SpecialEvent = new CustomEvent(
  "SpecialMessage",
  {
   detail:
   {
     message: "Hello There",
     time: new Date()
   },
   bubbles: true,
   cancelable: true
  });

【问题讨论】:

  • 看看MSDN 怎么说?为什么是 [Java] 标签?
  • 去掉多余的标签

标签: javascript html


【解决方案1】:

MDN 为 IE >= 9 提供了一个 polyfill。见下文。
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

(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;
})();

【讨论】:

【解决方案2】:

这应该适用于 IE9+

var SpecialEvent = document.createEvent("CustomEvent");
SpecialEvent.initCustomEvent('SpecialMessage', false, false, {
  detail: {
    message: "Hello There",
    time: new Date()
  },
  bubbles: true,
  cancelable: true
});

从这里接……Why aren't my parameters getting passed through to a dispatched event?

【讨论】:

    【解决方案3】:

    通过切换到 jQuery 事件而不是使用一些特殊的原型酱来让 IE 工作,使用更少的时间和精力并为自己节省未来的困难。 jQuery事件有更好的实现,兼容IE。

    [除非您是跨帧触发事件,否则您需要制作原型并使用传统的window.dispatchEvent(evt)]

    老办法:

    var SpecialEvent = new CustomEvent(
      "SpecialMessage",
      {
       detail:
       {
         message: "Hello There",
         time: new Date()
       },
       bubbles: true,
       cancelable: true
      });
    

    新方法:

    $(window).trigger("SpecialMessage", ["Hello There", new Date()]);
    

    并捕捉该事件:

    $(window).on("SpecialMessage",function(e, arg1, arg2){
        console.log(arg1);   // Hello There
        console.log(arg2);   // 2018-04-18...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-22
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多