最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery each() with setInterval - Stack Overflow

programmeradmin1浏览0评论

I have an object filled with various elements that I wish to iterate through using each() and then perform an action on the element whose turn it is. So:

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() is a basic shuffle function )

What I can't figure out is how to access the current element as a selector and perform an action on it. $(this) is $(window).

Finally I would then need the function to start the iteration again once it reaches the end of art and keep on looping ad infinitum.

I have an object filled with various elements that I wish to iterate through using each() and then perform an action on the element whose turn it is. So:

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() is a basic shuffle function )

What I can't figure out is how to access the current element as a selector and perform an action on it. $(this) is $(window).

Finally I would then need the function to start the iteration again once it reaches the end of art and keep on looping ad infinitum.

Share Improve this question asked Sep 25, 2012 at 18:03 artparksartparks 7611 gold badge10 silver badges25 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

If you're using setInterval, you'd get identical results swapping the order:

setInterval(function() {
    $(arts).each(function(){
         doSomethingWith(this);
    });   
}, 2000);

I don't think you want what you think you do here. I reckon you want:

var i = 0;
setInterval(function() {
    var art = arts[i++];
    doSomethingWith(art)
    if(i >= arts.length) i = 0;
}, 2000); 

jQuery's .each(...) method passes the "current" element (and its index) into the callback. this is just a convenience for when you don't need to do anything too complicated.

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

Above, the current element is available within the setInterval callback as current, for example. Note that this element is passed in its "raw" form, as this is, so if you want to call jQuery methods on it, you'll need to wrap it in the same way, ie: $(current).

Use that.

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

评论列表(0)

  1. 暂无评论