javascript - 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
});
知道为什么吗?
解决方案
好吧,我自己,
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 上使用它。
希望可以帮助某人。
推荐阅读
- javascript - 在 Django 3 中,如何使用 Javascript 访问我的模板目录?
- shell - 使用 sed 和 hdfs ls 进行更多优化
- azure - Azure Pipelines - 在管道之间共享装载以进行缓存?
- java - 按 XML 文档拆分 XML 流
- android - Android Kotlin Firebase 实时数据库:RecyclerView 显示为空
- git - VisualSVN 服务器
- npm - OctoberCMS 在插件中包含 JavaScript 供应商包
- kubernetes - 等待集群初始化超时,节点自动升级失败/或运行出错
- java - lombok 可以同时生成静态和非静态构造函数吗?
- python - MQTT 订阅比发布慢得多