代码之家  ›  专栏  ›  技术社区  ›  Nelson Rothermel

jQuery-选择不包含在另一个类中的类[重复]

  •  2
  • Nelson Rothermel  · 技术社区  · 14 年前

    可能重复:
    jQuery filtering selector to remove nested elements matching pattern.

    我有一个阶层的团体。类似于:

    <div class="group">
        <span class="child"></span>
        <div class="group">
            <span class="child"></span>
            <span class="child"></span>
            <span class="child"></span>
        </div>
        <span class="child"></span>
        <span class="child"></span>
        <div>This child is farther down <span class="child"></span></div>
    </div>
    

    如何在不选择任何子组的子组的情况下选择每个组中的子组?

    $(".group").each(function() {
        // Wrong, click fires twice (the 1st level group selects 2nd level children)
        var children = $(this).children(".child");
    
        // Wrong, click fires twice
        children = $(this).children(":not(.group) .child");
    
        // How can I properly do this??
    
        children.click(function() {
            alert("children.click");
        });
    });
    

    我也试过 find() 而不是 children() 但我似乎不能让它正常工作。而且,我不能直接使用孩子(或者 >

    3 回复  |  直到 8 年前
        1
  •  1
  •   Nikita Rybak    14 年前

    如果 .child 一直是它的直系后代,那么 > 选择器将工作,如前所述。否则,可以使用函数筛选集合

    var group = this;
    $(group).find('.child').filter(function() {
        // check if current element belongs to our group
        return $(this).closest('.group')[0] == group;
    })
    

    An example

        2
  •  1
  •   Community CDub    8 年前

    如果您只想要一个组的直系子代,可以尝试以下方法:

    $('.group > .child').click(function(){
        alert('You clicked on: '+$(this).text());
    });
    

    jQuery: child-selector

    编辑:否则您可能要签出 duplicate question gnarf发布

        3
  •  0
  •   Josiah Ruddell    14 年前

    试试这个,它也很可读:

    $(".group").each(function() {
      var allChilds = $(this).find('.child');
      var subChilds = $(this).find('.group .child');
    
      var firstChilds = allChilds.not(subChilds);
      firstChilds.css({ color: 'red' });
    });