jQuery infinite loop through each div

2019-02-23 17:01发布

问题:

I have some divs with divs in them, which I want to loop through while removing a class from the current one, then adding a class to the next one.

Then when I reach the last one, I want to go back to the start and do it all over again.

I already have a way of doing this, but it only works for one set of divs, I'm going to be having many sets of divs that need to loop independently.

Here's an example few sets (there would be a random amount of divs in each):

<div class="set">
    <div class="current">Item1</div>
    <div>Item2</div>
    <div>Item3</div>
</div>


<div class="set">
    <div class="current">Item1</div>
    <div>Item2</div>
    <div>Item3</div>
    <div>Item4</div>
    <div>Item5</div>
</div>

I need to remove that current class, and add it to the next div in each set, and so on.

Here is the code I have that works with one set:

$(function() {
    var items = $('.set div').length;
        current = 0;

    setInterval(function() {
        $('.set div').eq(current).removeClass('current');

        if (current == items - 1){
            current = 0;
        } else {
            current++;
        }

        $('.set div').eq(current).addClass('current');
    }, 500);
});

回答1:

my take:

http://jsfiddle.net/yyY28/

$('.set').each(function(){
    (function($set){
        setInterval(function(){
            var $cur = $set.find('.current').removeClass('current');
            var $next = $cur.next().length?$cur.next():$set.children().eq(0);
            $next.addClass('current');
        },1000);
    })($(this));

});​

version 2:

​setInterval(function(){
    $('.set').each(function(){
        var $cur = $(this).find('.current').removeClass('current');
        var $next = $cur.next().length?$cur.next():$(this).children().eq(0);
        $next.addClass('current');
    });
},1000);​


回答2:

Maybe I didn't get you right, but is that you are looking for?

function loop() {
    $(".set").each(function() {
        var current = $(this).children(".current").removeClass("current");
        var i = current.next().length ? current.index() : 0;
        current.siblings(":eq(" + i + ")").addClass("current");
    });
}

setInterval(loop, 500);​

DEMO: http://jsfiddle.net/jGcsh/



回答3:

try this one:

function changeCurrent(){
    $('.set').each(function(){
        var currentSubDiv = $(this).children('.current');
        currentSubDiv.removeClass('current');
        currentSubDiv.next().addClass('current');
    })
}

setInterval(changeCurrent,timeInMillis);