Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - How to cycle through siblings using jQuery?

I have the folowing code:

html:

<div class="container">
    <div class="selected">A</div>
    <div>B</div>
    <div>C</div>
    <div>D</div>
</div>
<button id="next">next!</button>

jQuery:

$("#next").click(function() {
    $(".selected").removeClass("selected").next().addClass("selected");
});

What i want is loop through the divs in the container. I can do this to cycle:

$("#next").click(function() {
    if ($(".selected").next().length == 0) {
        $(".selected").removeClass("selected").siblings(":nth-child(1)").addClass("selected");
    }
    else {
        $(".selected").removeClass("selected").next().addClass("selected");
    }
});

But i think there is a simpler way. How can i make it simpler ? (I don't mind if you don't use the next() function).

jsFiddle: http://jsfiddle.net/S28uC/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...