Gaw*_*wet 1 javascript foreach internet-explorer ecmascript-5 internet-explorer-11
forEach 循环应该在 IE11 和 diplay 中工作
对象不支持属性或方法“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
});
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?
嗯,我自己
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
});
Run Code Online (Sandbox Code Playgroud)
或者:
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
});
Run Code Online (Sandbox Code Playgroud)
总结一下: 确保您在 Array 对象而不是 NodeList 上使用它。
希望可以帮助某人。
| 归档时间: |
|
| 查看次数: |
4884 次 |
| 最近记录: |