我最近一直在研究JavaScript,一切都很好,直到我在 IE11 中打开我的页面。 IE9支持Mozilla website .forEach
。
这是我得到的错误。
SCRIPT438:Object不支持属性或方法'forEach'
这是代码。
var link1 = document.querySelectorAll("nav a");
var textbox = document.getElementById("OutputWindow");
link1.forEach(function (element) {
textbox.innerHTML += "<br/>" + element + "\n";
element.onclick = function () {
alert("Hello!");
console.log("hello!");
confirm("Hello!");
};
});
我尝试了polyfill,但令我高兴的是,Array
在 IE11 中有一个forEach
。
然后我出错了?
PS:这在Chrome中运行良好。
答案 0 :(得分:19)
终于神秘解决了。
显然,IE9及更高版本支持Array.forEach
,但NodeList
不支持querySelector
。我尝试Array.from()
无效,因为它需要 ES6 或使用 ES6-shim 。
我所要做的只是将nodeList
转换为Array
,我就这样做了。
Array.prototype.slice.call(document.querySelectorAll("nav a"), 0);
出现在问题In Javascript, what is the best way to convert a NodeList to an array
中答案 1 :(得分:1)
if (typeof Array.prototype.forEach != 'function') {
Array.prototype.forEach = function (callback) {
for (var i = 0; i < this.length; i++) {
callback.apply(this, [this[i], i, this]);
}
};
}
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
答案 2 :(得分:1)
为避免每次forEach()
调用都更改代码,以下是一个适合我的polyfill。在forEach()
上运行NodeList
时,它很简单,建议在https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach中使用。
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
答案 3 :(得分:0)
我正在这样做:
Array.from(document.querySelectorAll(someElements))
对我来说,答案仅仅是:
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
确保在节点列表中也存在forEach。