jq 组装数组_拼接jQuery元素数组

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

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?

  • item 1
  • item 1
  • item 1
  • item 1
  • item 1
  • item 1
  • item 1

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);

You'll notice in the console, every other item is still in the array.

解决方案

This code should work:

var $modules = $('.module');

$modules.each(function(i) {

var $el = $modules.eq(0);

$modules.splice(0, 1);

$el.addClass("fadein").removeClass('module');

});

EXPLAINATION

When you use each method, jQuery call your callback for each element, passing i as an index of current element.

So let's say you have an array: [elem1, elem2, elem3, elem4].

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.

As you can see you jumped over elem2. Thats why some elements remain in an array.

To avoid this behavior you have to use zero index: var $el = $modules.eq(0); and $modules.splice(0, 1);

This is a demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值