繁体   English   中英

使用setInterval jquery each()

[英]jquery each() with setInterval

我有一个填充了各种元素的对象,我希望使用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的回调作为内可用的current ,例如。 需要注意的是该元素在其“原始”的形式通过,因为this是,如果你想调用它的jQuery方法,你需要将其包装以同样的方式,即: $(current)

用那个。

$(arts).each(function(){
    var that = this;
    setInterval(function() {
    // in here perform an action on the current element in 'arts'
         doSomethingWith(that)
    }, 2000);   
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM