Internet Explorer 11中的SCRIPT438错误

时间:2016-12-25 13:29:36

标签: javascript internet-explorer foreach

我最近一直在研究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中运行良好。

4 个答案:

答案 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。