将 NodeList 转换为数组
我很难在 IE 8 中将 NodeList
转换为数组。以下内容在 Chrome 中完美运行,但在 IE 8 中 toArray()
不被识别为有效:
NodeList.prototype.toArray = function() {
var a = [];
for (var i = 0, len = this.length; i < len; i++) {
a[i] = this[i];
}
return a;
}
document.all.tags("div").toArray();
我尝试将原型函数添加到数组中只是为了检查我的理智并且它工作正常。这让我觉得 IE 8 实际上并没有返回 NodeList ?这是一个完整的示例:
我做错了什么?
I'm having a hard time converting a NodeList
to an array in IE 8. The following works perfectly in Chrome, but in IE 8 toArray()
is not recognized as valid:
NodeList.prototype.toArray = function() {
var a = [];
for (var i = 0, len = this.length; i < len; i++) {
a[i] = this[i];
}
return a;
}
document.all.tags("div").toArray();
I tried adding a prototype function to an array just to check my sanity and it works correctly. That makes me think IE 8 doesn't actually return a NodeList
? Here's a full example:
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您正在寻找使用 ES6 的现代答案:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
If you're looking for a modern answer using ES6:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
老问题,但这是一个尝试过的问题true 方法:
说明
document.querySelectorAll
使用 CSS 样式选择器来查找元素并返回节点列表。它从 IE 8 开始工作。slice
方法将类数组集合的一部分(在本例中为全部)复制到新数组中。call
允许您借用一个对象的方法以在另一个对象上使用。要查找节点列表,您也可以使用“document.getElementsByTagName()”,但这个更灵活。
Old question, but here is a tried & true method:
Explanation
document.querySelectorAll
uses a CSS-style selector to find elements and returns a node list. It works as of IE 8.slice
method copies a portion of an array-like collection (in this case all of it) into a new array.call
allows you to borrow a method from one object to use on anotherTo find the node list you could also have used `document.getElementsByTagName(), but this one is more flexible.
首先,不要使用
document.all
——它是非标准的并且已被弃用。使用document.getElementsByTagName
获取您案例中的 DIV 元素。其次,不要扩展 DOM 对象,例如
NodeList
——内置对象是一个非常奇怪的品种,不需要像您通常使用的任何其他对象一样运行。请参阅这篇文章以获得对此的深入解释:扩展DOM。First, don't use
document.all
-- it's non-standard and deprecated. Usedocument.getElementsByTagName
to get the DIV elements in your case.Second, don't extend DOM objects such as
NodeList
-- built-in objects are a very strange breed and are not required to behave like any other objects that you generally work with. See this article for an in-depth explanation of this: What's wrong with extending the DOM.IE 不支持标准方式的
NodeList
。这就是为什么您应该推出自己的命名空间而不是扩展浏览器核心对象。您可以执行
alert( typeof window.NodeList )
并查看它是否未定义。IE doesn't support
NodeList
in the standard way. This is why you should roll your own namespace and NOT extend browser core objects.You can do
alert( typeof window.NodeList )
and see if it's undefined or not.