首页 > 解决方案 > Javascript - forEach() 循环在 IE11 上不起作用

问题描述

forEach 循环应该在 IE11 和显示中工作

对象不支持属性或方法“forEach”。

它应该可以工作,因为它是 ECMAScript-5 函数并且IE11 支持它

但是,我的代码在这里不起作用:

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

知道为什么吗?

标签: javascriptinternet-explorerforeachinternet-explorer-11ecmascript-5

解决方案


好吧,我自己,

forEach() 实际上是在 IE11 上工作的,只是要小心你如何称呼它。

querySelectorAll()是一种返回NodeList的方法。在 Internet Explorer 上,foreach()仅适用于 Array对象。(它适用于带有 ES6 的 NodeList,IE11 不支持)

为了解决这个问题,有些人会建议使用 polyfill,它可以很好地工作,但您也可以使用 slice.call() 方法简单地将 NodeList 转换为数组:(在此处解释)

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
var alltableArray= Array.prototype.slice.call(alltable);
    alltableArray.forEach(function(element) {
                // Do some code
                });

或者:

var alltable = Array.prototype.slice.call(document.querySelectorAll('*[id^="table_"]')); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

总结一下: 确保您在 Array 对象而不是 NodeList 上使用它。

希望可以帮助某人。


推荐阅读