简体   繁体   English

jquery选择兄弟姐妹'直到'

[英]jquery select siblings 'until'

I have a DOM in the form of 我有一个DOM的形式

<input class="parent"></div>
<input class="child"></div>
<input class="child"></div>
<input class="parent"></div>
<input class="child"></div>
...

which I know is not Right and the right way to do this would be to reform the HTML, but lets say that is not possible. 我知道这是不对的,这样做的正确方法是改革HTML,但是我们说这是不可能的。

How can I get jquery to select all children of one parent (that is select all .children until .parent) 我怎样才能让jquery选择一个父母的所有孩子(即选择所有.children直到.parent)

jQuery 1.4 now has the .nextUntil(selector) function: jQuery 1.4现在有.nextUntil(选择器)功能:

    $('div.parent').toggle(
        function() {
            $(this).nextUntil('div.parent').hide();
         },
        function() {
            $(this).nextUntil('div.parent').show();
        }
    );

You can iterate through the nextAll div siblings elements until you find the following .parent , check this example : 您可以遍历nextAll div兄弟元素直到找到以下.parent ,请检查以下示例

$('.parent').click(function() {
  $(this).nextAll('div').each(function() {
    if ($(this).is('.parent')) {
      return false; // next parent reached, stop
    }
    $(this).toggleClass('highlight');
  });
});

Markup used: 标记使用:

<div class="parent">parent 1</div>
<div class="child">child</div>
<div class="child">child</div>
<div class="parent">parent 2</div>
<div class="child">child</div>
<div class="parent">parent 3</div>
<div class="child">child</div>
<div class="child">child</div>
<div class="child">child</div>

... ...

* See @foson answer for jquery 1.4+ * *请参阅@foson回答jquery 1.4+ *

Check out Ben Almans until utils . 看看Ben Almans 直到utils

It gives you 3 usefull methods: nextUntil, prevUntil, parentsUntil. 它为您提供了3种有用的方法:nextUntil,prevUntil,parentsUntil。

I think no need for the above custom functions, JQuery supports this functionality by nextUntil(selector, filter) function, but you should add filter to only apply your script to the filtered elements not to all next elements: 我认为不需要上面的自定义函数,JQuery通过nextUntil(selector, filter)函数支持这个功能,但你应该添加过滤器,只将你的脚本应用于过滤后的元素而不是所有下一个元素:

//hide all .child elements
$('div.child').hide();
$('div.parent').click(function() {
  //Toggle (show or hide) only .child elements until finding .parent element.
  $(this).nextUntil('div.parent', 'div.child').slideToggle('slow');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM