gpt4 book ai didi

Javascript .removeChild() 只删除偶数节点?

转载 作者:行者123 更新时间:2023-11-29 20:08:20 26 4
gpt4 key购买 nike

我正在尝试在 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>

最佳答案

问题是您在循环遍历集合时正在修改它。反向迭代应该可以解决这个问题......

for(i = chlds.length-1; i >= 0; i--)
{
if(!(chlds[i].nodeType == 3))
{
prnt.removeChild(chlds[i]);
}
}

关于Javascript .removeChild() 只删除偶数节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com