问题描述
我正在尝试使用splice()
从jQuery对象中删除元素.
但是,最终发生的是其他所有项目都被删除了.我假设这是由于使用了splice重新索引.
我要淡入每个<li>
,所以我需要从顶部开始.
有什么方法可以做到这一点,或者比我在这里做的更好的方法?
I'm trying to remove elements from a jQuery object using splice()
.
But, what ends up happening is every other item is removed.I'm assuming this is due to a re-index of using splice.
I was to fade in each <li>
so I need to start at the top.
Is there a way to accomplish this, or perhaps a better way than what I'm doing here?
<ul>
<li class="module">item 1</li>
<li class="module">item 1</li>
<li class="module">item 1</li>
<li class="module">item 1</li>
<li class="module">item 1</li>
<li class="module">item 1</li>
<li class="module">item 1</li>
</ul>
<script>
var $modules = $('.module');
$modules.each(function(i, el) {
var $el = $modules.eq(i);
$modules.splice(i, 1);
$el.addClass("fadein").removeClass('module');
});
console.log($modules);
</script>
您会在控制台中注意到,所有其他项仍在数组中.
You'll notice in the console, every other item is still in the array.
jsFiddle: http://jsfiddle.net/tvWUc/5/
jsFiddle: http://jsfiddle.net/tvWUc/5/
推荐答案
此代码应该有效:
var $modules = $('.module');
$modules.each(function(i) {
var $el = $modules.eq(0);
$modules.splice(0, 1);
$el.addClass("fadein").removeClass('module');
});
说明
使用each
方法时,jQuery会为每个元素调用回调,并将i
作为当前元素的索引传递.
When you use each
method, jQuery call your callback for each element, passing i
as an index of current element.
因此,假设您有一个数组:[elem1, elem2, elem3, elem4]
.
So let's say you have an array: [elem1, elem2, elem3, elem4]
.
在第一步中,i
等于0.因此,通过编写$el = $modules.eq(i);
,您将按预期获得第一个元素.然后您将其从数组数组中删除,现在看起来像这样:[elem2, elem3, elem4]
.在第二步中,i
等于1,这意味着数组的第二个元素,实际上是elem3.
On the first step i
equals 0. So by writing $el = $modules.eq(i);
you get the first element, as expected. then you remove it form array, and now it looks like that: [elem2, elem3, elem4]
.On the second step i
equals 1, which means second element of your array, that is elem3 actually.
如您所见,您跳过了elem2.这就是为什么某些元素保留在数组中的原因.
As you can see you jumped over elem2. Thats why some elements remain in an array.
要避免这种情况,您必须使用零索引:var $el = $modules.eq(0);
和$modules.splice(0, 1);
To avoid this behavior you have to use zero index: var $el = $modules.eq(0);
and $modules.splice(0, 1);
这是演示
这篇关于拼接jQuery元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!