我正在尝试在 ID="prnt" 的 DIV 下动态添加子 DIV。添加节点工作正常没问题。然而,对于已删除的节点,它只删除包括 0 在内的偶数节点就足够奇怪了。为什么会这样,我可能有点愚蠢,但它看起来更像是一个错误。我可能是非常错误的。
<script type="text/javascript">
function displayNodes()
{
var prnt = document.getElementById("prnt");
var chlds = prnt.childNodes;
var cont = document.getElementById("content");
for(i = 0; i < chlds.length; i++)
{
if(chlds[i].nodeType == 1)
{
cont.innerHTML +="<br />";
cont.innerHTML +="Node # " + (i+1);
cont.innerHTML +="<br />";
cont.innerHTML +=chlds[i].nodeName;
cont.innerHTML +="<br />";
}
}
}
function deleteENodes()
{
var prnt = document.getElementById("prnt");
var chlds = prnt.childNodes;
for(i = 0; i < chlds.length; i++)
{
if(!(chlds[i].nodeType == 3))
{
prnt.removeChild(chlds[i]);
}
}
}
function AddENodes()
{
var prnt = document.getElementById("prnt");
//Only even nodes are deletable PROBLEM
for(i = 0; i < 10; i++)
{
var newDIV = document.createElement('div');
newDIV.setAttribute("id", "c"+(i));
var text = document.createTextNode("New Inserted Child "+(i));
newDIV.appendChild(text);
prnt.appendChild(newDIV);
}
}
</script>
<title>Checking Div Nodes</title>
</head>
<body>
<div id="prnt">
Parent 1
</div>
<br />
<br />
<br />
<button type="button" onclick="displayNodes()">Show Node Info</button>
<button type="button" onclick="deleteENodes()">Remove All Element Nodes Under Parent 1</button>
<button type="button" onclick="AddENodes()">Add 5 New DIV Nodes</button>
<div id="content">
</div>
</body>