如何使用jQuery循环兄弟姐妹? [英] How to cycle through siblings using jQuery?

查看:214
本文介绍了如何使用jQuery循环兄弟姐妹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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");
});

我想要的是循环容器中的div。我可以这样做循环:

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");
    }
});

但我认为有一种更简单的方法。我怎样才能让它变得更简单? (我不介意你不使用 next()函数)。

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:< a href =http://jsfiddle.net/S28uC/ =noreferrer> http://jsfiddle.net/S28uC/

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

推荐答案

我更喜欢 siblings.first()而不是兄弟姐妹(:nth-​​child(1) ),但实际上,如果不使用 next()的一些变体,你将无法回头。长度

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");
});

这种方法有两个因素:


  1. 当你想无限期地循环收集时,会想到模数

  2. 去掉如果制作更加智能的代码

  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

设置 divs 的值时我更喜欢 $ selected.parent()。children()超过等价的 $ selected.siblings()。add($ selected)作为品味问题 - 几乎有无穷无尽的可能性。

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.

这篇关于如何使用jQuery循环兄弟姐妹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆