在`for`循环中调用`.remove()`并不会删除所有元素 [英] Calling `.remove()` inside `for` loop doesn't remove all elements

查看:52
本文介绍了在`for`循环中调用`.remove()`并不会删除所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery中使用一个简单的 for 循环.在下面的示例中,如果我删除调用 .remove()函数的行,则 console.log 输出所有元素.但是,如果我将调用添加到 .remove(),它将不再记录所有元素.

I use a simple for loop in jQuery. In the example below, if I delete the line calling the .remove() function, console.log outputs all elements. But if I add the call to .remove() it doesn't log all the elements anymore.

我在做什么错了?

注意:

我知道我可以使用 $('.list').remove()删除所有元素,但这只是一个示例.我想知道循环未按预期运行的原因.

I know I can use $('.list').remove() to remove all elements, but this just an example. I would like to know the reason why the loop doesn't run as expected.

我还尝试了 .each()函数,它运行良好.但是我想用 for 循环找到解决方案.

I also tried the .each() function and it worked fine. But I want find a solution with the for loop.

http://jsfiddle.net/53HzV/1/

$('.btn').click(function(){
    for (var i = 0; i < $('.list').length; i++) {
        console.log($('.list').eq(i));

        $('.list').eq(i).remove();
    }
});


<div class="list">list</div>
<div class="list">list</div>
<div class="list">list</div>
<div class="list">list</div>

<div class="btn">btn</div>

推荐答案

以下是您的代码正在做的事情:

Here is what your code is doing:

第一个循环:i = 0,4格(长度= 4),删除第一个(索引0)

First loop: i=0, 4 divs (length=4), remove the first one (index 0)

第二个循环:i = 1,3格(长度= 3),删除第二个(索引1)

Second loop: i=1, 3 divs (length=3), remove the second one (index 1)

第三循环:i = 2,2格(长度= 2),不执行任何操作,因为i = length

Third loop: i=2, 2 divs (length=2), do nothing as i=length

很明显,您的代码将在第三个循环处中断.

Obviously your code will break at the third loop.

这篇关于在`for`循环中调用`.remove()`并不会删除所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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