removechild 循环在完成前退出 [英] removechild loop exits before finish

查看:26
本文介绍了removechild 循环在完成前退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码,它查找文档中类名为 foo 的所有元素,然后将它们全部删除

I have the following piece of code that finds all elements in the document with classname foo and then removes them all

        function(doc) {
            var items = doc.getElementsByClassName('foo');
            alert(items.length);
            if(items.length>0) {
                for(var i=0;i<items.length;i++) {
                    alert(i);
                    doc.body.removeChild(items[i]);
                }
        }

例如,items.length 为 3,函数在运行一个循环后退出,当长度为 8 时,它在 3 处退出.任何帮助将不胜感激.此外,当我一次又一次地运行该函数时,它最终会删除所有元素.

Forexample, the items.length is 3 and the function exits after running one loop and when the length is 8 it exits at 3. Any help would be greatly appreciated. Also, when I run the function again and again it does eventually remove all elements.

推荐答案

问题在于 items 是一个 live NodeList,即每当您访问列表的属性 (items.length),将重新评估列表(再次搜索元素).
由于您同时删除了元素,列表会变短,但您保留索引.

The problem is that items is a live NodeList, i.e. whenever you access a property of the list (items.length), the list is reevaluated (elements are searched again).
Since you delete elements in the meantime, the list becomes shorter, but you keep the index.

您可以先将 NodeList 转换为数组:

You could convert the NodeList to an array first:

var items = [].slice.call(doc.getElementsByClassName('foo'));

删除 DOM 元素时数组大小不会改变.

The array size won't change when you delete the DOM elements.

这篇关于removechild 循环在完成前退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆