开发者

JavaScript Traverse Table Issue

开发者 https://www.devze.com 2022-12-21 14:39 出处:网络
Why does this script bail out (IE) or stick (FF) at the first table cell containing text that it finds?

Why does this script bail out (IE) or stick (FF) at the first table cell containing text that it finds?

<!html>
<head>
<script type="text/javascript">
function CheckChildren(obj)
{
        alert(obj.id + ' ' + obj.tagName + ' ' + obj.childNodes.length);
        for ( i = 0; i < obj.childNodes.length; i++)
        {
                CheckChildren(obj.childNodes[i]);
        }
        alert(obj.id);
        return false;
}
开发者_开发知识库</script>
</head>
<body>

<table id="table">
<tr id="a"><td id="b">b</td><td id="c">c</td></tr>
<tr id="d"><td id="e">e</td><td id="f">f</td></tr>
</table>
<input type="button" onclick="CheckChildren(document.getElementById('table'))" value="click">
</body>
</html>


Try putting the word "var" before the "i" in your for loop.

  for ( var i = 0; i < obj.childNodes.length; i++)

Without that, your code is referring to a global variable "i", so each recursive iteration sets it back to zero.

0

精彩评论

暂无评论...
验证码 换一张
取 消