Javascript,查看"对象节点列表"

Rya*_*yan 9 javascript nodelist

在我的一个变量上做一个alert()给了我这个结果

  [object NodeList]
Run Code Online (Sandbox Code Playgroud)

我怎样才能看到其中的所有值?

注意; 我在Firefox上,不知道如何使用chromebug,所以它没有安装.

aro*_*oth 10

您可以NodeList按照与数组相同的方式迭代值:

for (var index = 0; index < nodeList.length; index++) {
    alert(nodeList[index]);
}
Run Code Online (Sandbox Code Playgroud)

这是一个很好的资源,有一些更深入的信息:http: //reference.sitepoint.com/javascript/NodeList

  • 我认为它应该是"nodeList [index]"而不是"nodeList [i]",因为我没有在任何地方定义.. (3认同)
  • @Ryan - 是的,因为`NodeList`充满了`Nodes`.您是否尝试输出某些特定属性?如果是这样,你可以做`alert(nodeList [i] .attribute)`.或者你可能想尝试`alert(nodeList [i] .innerHTML)`. (2认同)

Jua*_*des 7

更好的选择是不使用alert,因为它将显示对象的toString().使用来自FF和Chrome的console.log将为您提供一个很好的可扩展对象,您可以单击该对象进行钻取

如果你真的需要序列化,你可以使用outerHTML

// Firefox doesn't support outerHTML on nodes, so here's a method that does it
// http://stackoverflow.com/questions/1700870/how-do-i-do-outerhtml-in-firefox
function outerHTML(node){
    return node.outerHTML || new XMLSerializer().serializeToString(node);
}

for (var index = 0; index < nodeList.length; index++) {
    alert(outerHTML( nodeList[i] ) );
}
Run Code Online (Sandbox Code Playgroud)