【问题标题】:jquery select siblings 'until'jquery选择兄弟姐妹'直到'
【发布时间】:2009-12-02 00:00:39
【问题描述】:

我有一个 DOM 的形式

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

我知道这是不对的,正确的方法是改革 HTML,但可以说这是不可能的。

如何让 jquery 选择一个父母的所有孩子(即选择所有 .children 直到 .parent)

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    jQuery 1.4 现在有了 .nextUntil(selector) 函数:

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

    【讨论】:

      【解决方案2】:

      您可以遍历nextAll div 兄弟元素,直到找到以下.parent,检查此example

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

      使用的标记:

      <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>
      

      ...

      【讨论】:

      • 我会再试一次。我已经这样做了,但是由于我没有包含一些额外的 DOM 元素(包装器),它导致了很多缓慢。我没想过只返回 false (我一直在检查)。我会优化并再试一次。谢谢!
      • 这是一个巨大的帮助。谢谢!
      【解决方案3】:

      * 请参阅@foson 对 jquery 1.4+ 的回答 *

      查看 Ben Almans until utils

      它为您提供了 3 个有用的方法:nextUntil、prevUntil、parentsUntil。

      【讨论】:

      • 我最终使用了这个实用程序,非常容易并且可以完成上述操作,但我不必维护它;)
      • 值得查看关于 nextUntil 的@foson 答案
      【解决方案4】:

      我认为不需要上述自定义函数,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');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-07
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 1970-01-01
        相关资源
        最近更新 更多