美文网首页
兼容IE下无法forEach NodeList的bug

兼容IE下无法forEach NodeList的bug

作者: MsgSS | 来源:发表于2019-04-01 10:57 被阅读0次

NodeList 对象是一个节点的集合,是由 Node.childNodesdocument.querySelectorAll返回的,实则是一个类数组对象

Although NodeList is not an Array, it is possible to iterate over it with forEach(). It can also be converted to a real Array using Array.from().
However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach() — see this document's Example.

在主流浏览器和高版本IE下,可以直接使用forEach进行遍历,但对于IE11以下的版本,将无法执行遍历,下面提供一种方法对低版本IE做兼容

NodeList.prototype.forEach = Array.prototype.forEach;

直接在NodeList对象原型上指定forEach为Array的forEach,从而实现了NodeList的forEach遍历。

相关文章

网友评论

      本文标题:兼容IE下无法forEach NodeList的bug

      本文链接:https://www.haomeiwen.com/subject/pbvmbqtx.html