Internet Explorer 11 问题:addEventListener 不起作用

2024-01-27

我正在尝试在元素列表上添加鼠标按下的侦听器事件。该代码适用于 chrome,但不适用于 IE

document.getElementsByClassName('select2-result-selectable').forEach(function(item){
  item.addEventListener('mousedown', function(e) { console.log( "User clicked on 'foo.'" ); 
  e.preventDefault();}); 
})

这适用于 Chrome,但不适用于 IE 11。

我也尝试了以下代码。

document.getElementsByClassName('select2-result-selectable').forEach(function(item){
    if (item.addEventListener){
        item.addEventListener('mousedown',function(e){ console.log(e); e.preventDefault(); 
        console.log( "User clicked on 'foo.'" );}) 
      } else if (item.attachEvent){
        item.attachEvent('mousedown',function(e){ console.log(e); e.preventDefault(); 
        console.log( "User clicked on 'foo.'" );})
      }
    })

但这又是徒劳的,它适用于 chrome,但不适用于 IE。有什么建议么?


我怀疑你会发现事实并非如此addEventListener这就是问题所在,尽管您的第二个代码块需要onmousedown而不仅仅是mousedown in the attachEvent调用(微软在事件名称上使用“on”前缀)。但IE11有addEventListener无论如何,只有当 IE11 自身步履蹒跚时,它才会丢失(您可以通过添加X-UA-Compatible标题到您的页面head):

<meta http-equiv="X-UA-Compatible" content="IE=edge">

...并在必要时关闭 Intranet 站点的“兼容性视图”。

But,我认为问题是你正在尝试使用forEach on an HTMLCollection。返回值getElementsByClassName isn't一个数组,它是一个HTMLCollection。规范没有要求HTMLCollection具有forEach(Chrome 将其添加为扩展)。forEach定义为NodeList(返回的类型querySelectorAll), 但不是HTMLCollection,并且该添加相对较新,并且在 IE 中不受支持。

所以要使用forEach,你会这样做:

Array.prototype.forEach.call(document.getElementsByClassName('select2-result-selectable', function(item) {
    // ...
});

或者,您可以填充forEach on HTMLCollection不过,很容易,如图所示我的回答在这里 https://stackoverflow.com/a/46929259/157247。这是一个同时执行这两项操作的循环NodeList(如有必要)和HTMLCollection(如果需要)和聚填充forEach(如果需要)和(对于有它的浏览器)Symbol.iterator(不过,IE11 不会,您可以选择保留该代码,尽管保留它是无害的):

var ctors = [typeof NodeList !== "undefined" && NodeList, typeof HTMLCollection !== "undefined" && HTMLCollection];
for (var n = 0; n < ctors.length; ++n) {
    var ctor = ctors[n];
    if (ctor && ctor.prototype && !ctor.prototype.forEach) {
        // (Yes, there's really no need for `Object.defineProperty` when doing the `forEach`)
        ctor.prototype.forEach = Array.prototype.forEach;
        if (typeof Symbol !== "undefined" && Symbol.iterator && !ctor.prototype[Symbol.iterator]) {
            Object.defineProperty(ctor.prototype, Symbol.iterator, {
                value: Array.prototype[Symbol.itereator],
                writable: true,
                configurable: true
            });
        }
    }
}

然后你的原始代码使用forEach on HTMLCollection会工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Internet Explorer 11 问题:addEventListener 不起作用 的相关文章

随机推荐