IE9不支持使用CustomEvent初始化的对象进行此操作

15

我在IE9中遇到以下错误:

"对象不支持此操作"。

关于此问题有很多疑问,但我的问题特别针对以下代码:

 var myEvent = new CustomEvent("additem");

据我所知,CustomEvent 在 IE9 中作为 DOM 操作命令得到了支持。在 Chrome 中可以正常工作,没有任何异常。

是否有人遇到过此问题并知道如何解决?谢谢。

4个回答

20

据我所知,IE浏览器不支持自定义事件,只有普通浏览器支持。建议使用提供跨浏览器实现的JavaScript库,例如jQuery的trigger: http://api.jquery.com/trigger/


1
看起来IE9现在没有自定义事件的构造函数http://msdn.microsoft.com/en-us/library/ie/ff975304%28v=vs.85%29.aspx,可以使用createEvent函数来创建示例,但没有构造函数。我同意Flunk的观点,如果您想要多浏览器支持,最好使用库。 - HMR
10
@HMR 是正确的,支持自定义事件!你需要使用document.createEvent()CustomEvent::initCustomEvent()以确保在IE 9中兼容性。在这里查看我的答案:https://dev59.com/G2Ik5IYBdhLWcg3wWtFz#19345563 - ComFreek

18
您可以使用 JavaScript 函数来检测浏览器是否为 IE11 或更低版本,然后应用下一个 polyfill:
    (function () {
      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;
    })();

上面的polyfill来自MDN: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent


1
这个 polyfill 似乎无法检测到何时从本地实现降级。 - goofballLogic
谢谢你,Alin!我编辑了我的回答并进行了修正。 - Florin Dobre
1
URL 应为:https://developer.mozilla.org/zh-CN/docs/Web/API/CustomEvent/CustomEvent - olefrank

6
尝试使用此polyfill,它不会替换原生(且可用)的CustomEvent方法。
(function () {
  try {
    new CustomEvent('test');
    return;
  } catch(e) {
    // ignore this error and continue below
  }

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

在IE11中,这对我没有起作用。调用new CustomEvent('test')实际上调用了此处定义的方法,导致填充程序永远不会被添加。 - anztenney
啊,有趣...也许尝试将其余部分移至catch块内? - Scott Jungwirth

1
以下 polyfill 不会替换原生的 CustomEvent(), 摘自:MDN CustomEvent()
(function () {

  if (typeof CustomEvent === 'function') { return; }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接