我试图用javascript遍历一个名为"playerhash“的xml文件中的所有元素。
for(var i = 0; i < 4; i++) {
alert(i);
if(getCookie('riskinfo') == xmldoc.getElementsByTagName("playerhash"[i].childNodes[0].nodeValue) {
player = xmldoc.getElementsByTagName("playerhash")[i].getAttribute('color');
break;
}
}当我尝试运行js时,它给出了带有Line 3: Uncaught TypeError: Cannot read property 'nodeValue' of undefined ()函数的警告,我发现错误是在i=0时发生的,并且我知道至少有四个playerhash元素。
如何才能遍历所有元素而不出现错误?
发布于 2011-08-15 11:49:38
正如deceze所说,你在代码中有错误。您应该以小得多的步骤编写代码,以便更容易调试。此外,在继续之前检查每个步骤,以便在意外失败时不会向用户抛出错误。条件表达式不应该进行赋值,因为这会使调试变得更加困难,只将它们用于测试条件:
// Should have already checked that xmldoc is a valid document
var riskinfo = getCookie('riskinfo');
var playerhash = xmldoc.getElementsByTagName("playerhash");
var max = 4; // or playerhash.length
var node, player;
for(var i = 0; i < max; i++) {
node = playerhash[i];
if (node && node.nodeValue == riskinfo) {
player = node.getAttribute('color');
i = max; // break out of for loop
}
}发布于 2011-08-15 11:05:03
.getElementsByTagName("playerhash"[i].childNodes[0].nodeValue)你里面少了一个)。应该是这样的:
if (getCookie('riskinfo') == xmldoc.getElementsByTagName("playerhash")[i].childNodes[0].nodeValue) {当然,在每个循环中重复xmldoc.getElementsByTagName("playerhash")是相当昂贵的,您应该在循环之前执行一次,并将结果保存在一个变量中。
在尝试访问那个子节点之前,您可能还应该检查ith元素是否实际存在,以及它是否确实有任何子节点。
https://stackoverflow.com/questions/7061315
复制相似问题