日期:2014-05-16  浏览次数:20357 次

DOM子节点比较问题?
<html>
<head> <title> Test </title>
<script   type= "text/javascript ">
function   nodecheck(parentNode,childNode)
{
var   childs=parentNode.childNodes;
for(var   i=0;i <childs.length;i++)
{
if(childs[i]==childNode)
return   true;
if(childs[i].hasChildNodes())
nodecheck(childs[i],childNode);
}
return   false;
}
var   testfun=function()
{
var   e1=document.getElementById( 'ROOT ');
var   e2=document.getElementById( 'A ');
alert(nodecheck(e1,e2));
}
</script>
</head>
<body   onload= "testfun(); ">
<div   id= "ROOT ">
<div   id= "A ">
<div   id= "AA ">
<div   id= "AAA ">
Hello
</div>
</div>
</div>
<div   id= "B ">
<p   id= "BA ">
<input   id= "BAA "   type= "text "   />
</p>
<p   id= "BB ">
<input   id= "BBA "   type= "button "   value= "lala "   />
</p>
</div>
<div   id= "C ">
<select   id= "CA ">
<option   id= "CAA "> 1 </option>
<option   id= "CAB "> 2 </option>
<option   id= "CAC "> 3 </option>
</select>
</div>
</div>
</body>
</html>
==============================================================
目的:输入一个节点A,再输入一个节点B,判断B节点是否是A节点的子节点
是返回true     否返回false

var   e1=document.getElementById( 'ROOT ');
var   e2=document.getElementById( 'A ');
返回true     A是ROOT的子节点

var   e1=document.getElementById( 'ROOT ');
var   e2=document.getElementById( 'AA ');

为什么返回false?
是这个比较判断   childs[i]==childNode     出现问题了么?

------解决方案--------------------
用遍历吧
判断B是否是A的子节点

function isChild(A,B){
for(var i=0;i <A.childNodes.length;i++){
if(A.childNodes[i]==B){
return true;
}
}
return false;
}
------解决方案--------------------
var testfun = function()
{
var e1 = document.getElementById( 'ROOT ');
var e2 = document.getElementById( 'A ');
while (e2.parentNode) {
if (e2 == e1)
return true;
e2 = e2.parentNode;
}
return false;
}
这样判断比较简单咯