I suspect you'll find that it's not addEventListener
that's the problem, although your second code block would have needed onmousedown
rather than just mousedown
in the attachEvent
call (Microsoft used the "on" prefix on event names).
(我怀疑您会发现问题不是由addEventListener
引起的,尽管您的第二个代码块将需要onmousedown
而不是仅仅在attachEvent
调用中mousedown
(Microsoft在事件名称上使用了“ on”前缀)。)
But IE11 has addEventListener
anyway, it would only be missing if IE11 were hobbling itself (which you can fix by adding the X-UA-Compatible
header to your page in head
):(但是IE11仍然具有addEventListener
,只有在IE11自己滚动时(它可以通过将X-UA-Compatible
标头添加到head
的页面中来解决),它才会丢失:)
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
...and turning off "compatibility view" for Intranet sites if necessary.
(...并在必要时关闭Intranet网站的“兼容性视图”。)
But , I think the problem is that you're trying to use forEach
on an HTMLCollection
.
(但是 ,我认为问题在于您正在尝试在HTMLCollection
上使用forEach
。)
The return value of getElementsByClassName
isn't an array, it's an HTMLCollection
.(getElementsByClassName
的返回值不是数组,而是HTMLCollection
。)
The spec doesn't require HTMLCollection
to have forEach
(Chrome adds it as an extension).(规范不需要HTMLCollection
具有forEach
(Chrome将其添加为扩展)。)
forEach
is defined for NodeList
(the type returned by querySelectorAll
), but not HTMLCollection
, and that addition is relatively new and not supported in IE.(forEach
是为NodeList
(由querySelectorAll
返回的类型)定义的,但不是HTMLCollection
,并且这种添加是相对较新的,并且在IE中不受支持。)
So to use forEach
, you'd do:
(因此,要使用forEach
,您需要这样做:)
Array.prototype.forEach.call(document.getElementsByClassName('select2-result-selectable', function(item) {
// ...
});
Alternatively, you can polyfill forEach
on HTMLCollection
easily, though, as shown in my answer here .
(另外,您也可以轻松地在HTMLCollection
上HTMLCollection
forEach
,如我在此处的答案所示。)
Here's a loop doing both NodeList
(if necessary) and HTMLCollection
(if necessary), and polyfilling forEach
(if necessary) and (for browsers that have it) Symbol.iterator
(IE11 doesn't, though, you may choose to leave that code off although it's harmless to leave it):(这是一个循环,同时执行NodeList
(如果需要)和HTMLCollection
(如果需要),以及polyfilling 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
});
}
}
}
Then your original code using forEach
on HTMLCollection
would work.
(然后,在HTMLCollection
上使用forEach
的原始代码将起作用。)