问题描述
我想取给定节点的子节点中已知id的目标节点。代码如下,但是当迭代找到目标节点后return不出来,而必须等待迭代结束。code:... <div id="div"> <pre> <div class="src"> <pre><div class="src"> <dl id="L1"> 1 </dl> <span class="comment"> </span> <dl id="L8"> 8 </dl> <dl id="L9"> 9 </dl> <span class="type">int</span> NeedXbridgeSwap = 0; <dl id="L10"> 10 </dl> <dl id="L11"> 11 </dl> <span class="directive">#include</span> <linux/types.h> <dl id="L12"> 12 </dl> </div> </pre> </div> </pre> </div> <div> <input type="button" value="find" onclick="getNode();"> </div></body></html><script>var result;function getNode(){ var node = document.getElementById("div"); alert(findAimNode(node, 'L8').id);} function findAimNode(node, aimId){ if(node.id == aimId){ return node; }else{ var children = node.childNodes; for(var i =0;i<children.length; i++){ if(children[i].nodeType != 1) continue; else findAimNode(children[i], aimId); } } }</script>
解决方案
你的这个方法findAimNode有问题,这样改不知道是不是你要的意思?(没有测试过)function findAimNode(node, aimId){ if(node.id == aimId){ return node; } var children = node.childNodes; for(var i =0;i<children.length; i++){ if(children[i].nodeType != 1) continue; else node = findAimNode(children[i], aimId); if(node.id == aimId){ return node; } } }