将NodeList转换为数组 [英] Convert NodeList to array

查看:321
本文介绍了将NodeList转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难将 NodeList 转换为IE 8中的数组。以下内容适用于Chrome,但在IE 8中 toArray()未被识别为有效:

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();

我尝试将一个原型函数添加到数组只是为了检查我的理智并且它正常工作。这让我觉得IE 8实际上并没有返回 NodeList ?以下是一个完整的示例:

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:

http://jsfiddle.net/e4RbH/

我做错了什么?

推荐答案

首先,不要使用 document.all - 它是非标准的并且已弃用。使用 document.getElementsByTagName 在你的情况下获取DIV元素。

First, don't use document.all -- it's non-standard and deprecated. Use document.getElementsByTagName to get the DIV elements in your case.

其次,不要扩展DOM对象,例如 NodeList - 内置对象是一种非常奇怪的品种,不需要像通常使用的任何其他对象一样运行。请参阅此文章以获得对此的深入解释:扩展DOM有什么问题

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.

这篇关于将NodeList转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆