我怀疑你会发现事实并非如此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
会工作。