for ...在循环中没有遍历所有属性?(for…in loop not looping through all properties?)

编程入门 行业动态 更新时间:2024-10-19 04:29:23
for ...在循环中没有遍历所有属性?(for…in loop not looping through all properties?)

当我加载我的页面时,会创建一个nodeList,它看起来像这样:

[text, h4, text, span, br, input, br, span, br, input, br, span, br, input, br, span, br, input, br]

我创建了一个简单的for循环,循环遍历所有这些元素,并从DOM中删除它们中的每一个。 (所有的元素都在<section> )

这是循环:

for(element in videoTitlesElement.childNodes){ if(!isNaN(element)){ videoTitlesElement.removeChild( videoTitlesElement.childNodes[element]); } }

但是,在循环结束时,nodeList看起来像这样:

[h4, span, input, span, input, span, input, span, input]

并非所有元素都被删除了。 为什么?

谢谢。

When I load my page, a nodeList gets created, and it looks like this:

[text, h4, text, span, br, input, br, span, br, input, br, span, br, input, br, span, br, input, br]

I created a simple for loop that loops through all these elements and deletes each one of them from the DOM. (all the elements are in a <section>)

Here's the loop:

for(element in videoTitlesElement.childNodes){ if(!isNaN(element)){ videoTitlesElement.removeChild( videoTitlesElement.childNodes[element]); } }

But, by the end of the loop, the nodeList looks like this:

[h4, span, input, span, input, span, input, span, input]

not all elements got removed. Why?

Thanks.

最满意答案

两件事情。 首先,在迭代数字索引时不要使用for ... in ; 使用普通的for循环。 那么你不会需要isNaN()检查,而且它通常更安全。

第二个问题是,当你删除一个孩子时,你改变了列表的长度。 如果您删除了0号孩子,那么曾经是孩子1的孩子会变成孩子0.因此,您真正想要的只是一个简单的while循环:

while (videoTitlesElement.childNodes.length) videoTitlesElement.removeChild(videoTitlesElement.childNodes[0]);

或者更简单:

while (videoTitlesElement.firstChild) videoTitlesElement.removeChild(videoTitlesElement.firstChild);

我还应该注意(假设你正在使用HTML DOM),通过简单地通过.innerHTML爆破,更容易清除元素的所有子节点:

videoTitlesElement.innerHTML = "";

Two things. First, don't use for ... in when you're iterating through numeric indexes; use a plain for loop. Then you won't need that isNaN() check, and it's generally safer.

The second problem is that when you remove a child, you change the length of the list. If you remove child 0, then the child that used to be child 1 becomes child 0. Thus, what you really want is a simple while loop:

while (videoTitlesElement.childNodes.length) videoTitlesElement.removeChild(videoTitlesElement.childNodes[0]);

or, simpler:

while (videoTitlesElement.firstChild) videoTitlesElement.removeChild(videoTitlesElement.firstChild);

I should also note (assuming you're working with an HTML DOM) that it's easier to clear out all the child nodes of an element by simply blasting it via .innerHTML:

videoTitlesElement.innerHTML = "";

更多推荐

本文发布于:2023-07-25 05:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   属性   loop   looping   properties

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!