How to cycle through siblings using jQuery?

前端 未结 4 1332
南旧
南旧 2020-12-11 18:24

I have the folowing code:

html:

A
B<
相关标签:
4条回答
  • 2020-12-11 18:42

    I 'd prefer siblings.first() instead of siblings(":nth-child(1)"), but in essence you won't be able to wrap around without using some variant of next().length.

    Update: If I were writing this from scratch, this is how I 'd do it:

    $("#next").click(function() {
        var $selected = $(".selected").removeClass("selected");
        var divs = $selected.parent().children();
        divs.eq((divs.index($selected) + 1) % divs.length).addClass("selected");
    });
    

    This approach is motivated by two factors:

    1. When you want to cycle over a collection indefinitely, modulo comes to mind
    2. Getting rid of the if makes for smarter-looking code

    When setting the value of divs I preferred $selected.parent().children() over the equivalent $selected.siblings().add($selected) as a matter of taste -- there are practically endless possibilities.

    0 讨论(0)
  • 2020-12-11 18:43

    You can try this

    var  cont   = $('.container'),
         i      = 0;
    $("#next").on('click', function() {
        cont.children().removeClass('selected');
        i += 1;
        if ( i === document.querySelectorAll('.container div').length ) { i = 0; }
        cont.children().eq(i).addClass('selected');
    });
    

    var cont	= $('.container'),
    	i 	    = 0;
        
    $("#next").on('click', function() {
        cont.children().removeClass('selected');
        
        // increase index for each click
        i += 1;
        // reset i if it reached to last index
        //(hack to force next to go back to first element when we are at the end)
        if ( i === document.querySelectorAll('.container div').length ) {
        		i	=	0;
        }
      
        cont.children().eq(i).addClass('selected');
    });
    .selected {
        background-color: yellow;   
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
        <div class="selected">A</div>
        <div>B</div>
        <div>C</div>
        <div>D</div>
    </div>
    
    <button id="next">next!</button>

    simply you will increase i for each click and when it reach the end (divs length ) it will be reset.

    0 讨论(0)
  • 2020-12-11 18:55

    One simple way is this :

    $("#container").find("div:eq(0)").addClass("selected");
    
    0 讨论(0)
  • 2020-12-11 19:05

    how about this.

    ...
    var selected = $(".selected").removeClass("selected");
    if (jQuery(selected).next().addClass("selected").length == 0
       {jQuery(selected).siblings().first().addClass("selected");};
    ...
    

    In old good AI manner you try to do the deed (addClass), if it worked (length <> 0) nothing more to do, otherwise you try again on the first of the siblings.

    0 讨论(0)
提交回复
热议问题