使用setInterval jquery each()
我有一个填充了各种元素的对象,我希望使用each()
进行迭代,然后对轮到它的元素执行操作。 所以:
var arts = $("#press-sqs > article"); shuffle(arts); $(arts).each(function(){ setInterval(function() { // in here perform an action on the current element in 'arts' }, 2000); });
( shuffle()
是一个基本的shuffle函数)
我无法弄清楚的是如何将当前元素作为选择器进行访问并对其执行操作。 $(this)
是$(window)
。
最后,我需要该函数在它到达art
结束时再次开始迭代并继续无限循环。
如果您正在使用setInterval
,那么您将获得相同的结果来交换订单:
setInterval(function() { $(arts).each(function(){ doSomethingWith(this); }); }, 2000);
我不认为你想要你在这里做什么。 我想你想要:
var i = 0; setInterval(function() { var art = arts[i++]; doSomethingWith(art) if(i >= arts.length) i = 0; }, 2000);
jQuery的.each(...)
方法将“current”元素(及其索引)传递给回调。 this
只是一个方便,当你不需要做任何太复杂的事情。
$(arts).each(function(i, current){ setInterval(function() { // in here perform an action on the current element in 'arts' }, 2000); });
例如,在上面,当前元素在setInterval回调中可用作当前元素。 请注意,此元素以“原始”forms传递,因此,如果您想在其上调用jQuery方法,则需要以相同的方式包装它,即: $(current)
。
用那个。
$(arts).each(function(){ var that = this; setInterval(function() { // in here perform an action on the current element in 'arts' doSomethingWith(that) }, 2000); });