代码之家  ›  专栏  ›  技术社区  ›  Sebastian P.R. Gingter

第一个层次结构元素的jquery选择器?

  •  0
  • Sebastian P.R. Gingter  · 技术社区  · 16 年前

    我有这个HTML结构:

    <div class="start">
      <div class="someclass">
        <div class="catchme">
          <div="nested">
            <div class="catchme"> <!-- STOP! no, no catchme's within other catchme's -->
            </div>
          </div>
        </div>
        <div class="someclass">
          <div class="catchme">
          </div>
        </div>
      </div>
      <div class="otherclass">
        <div class="catchme">
        </div>
      </div>
    </div>
    

    我正在寻找一个jquery结构,它返回“start”容器中的所有catchme,但找到的catchme中包含的所有catchme除外。事实上,我只想要所有的“第一级”catchme,不管它们在DOM树中有多深。

    这是附近的东西,但不是很好:

    var start = $('.start');
    // do smething
    $('.catchme:first, .catchme:first:parent + .catchme', start)
    

    我有点想在所有找到的元素之后,进一步打破对树的遍历。有什么想法吗?

    3 回复  |  直到 16 年前
        1
  •  3
  •   user113716    16 年前

    这样行吗?

    $('.catchme:not(.catchme .catchme)');
    
        2
  •  0
  •   drmonkeyninja    16 年前

    想要这个工作吗?

    $('.catchme :not(.catchme)', start)
    
        3
  •  0
  •   Felix Kling    16 年前

    你可以使用 .filter() .parents() :

    $('.catchme').filter(function(){
        return $(this).parents('.catchme').length == 0;
    };
    

    这将只选择那些 catchme 没有的元素 卡奇梅 元素作为祖先。