jQuery最接近排除self

Joe*_*ang 39 jquery

closest()将通过测试元素本身并遍历DOM树中的祖先来获得与选择器匹配的第一个元素.但我想知道是否有任何方法可以将结果排除在外(我的意思是得到它的父母).

让我举个例子.请检讨一下.

<div id='div1' class="container">
    <div id="div2" class="container">
        <!--many nested div.container as it directly or indirectly children -->
    </div>
    <div id="div3" class="container">
        <!--many nested div.container as it directly or indirectly children -->
    </div>
</div>

$(function() {

    $('div.container').on('mouseover', function(e){
        //I only want to select the first parent with the class container.
        //closest include the this element. 
        console.log($(this).closest('.container').attr('id'));
    });
});
Run Code Online (Sandbox Code Playgroud)

Fab*_*tté 93

在尝试查找.closest()祖先之前,您可以遍历一个级别:

$(this).parent().closest('.container');
Run Code Online (Sandbox Code Playgroud)


Joe*_*ang 1

正确答案是.parents('.container:first');谢谢

  • 从性能角度来看,“.parent().closest('.container')”应该表现得更好,因为它在匹配第一个元素后停止,这与“.parents()”不同,后者总是一直遍历到文档级别。 (17认同)
  • 嗯,是。当您不想匹配第一级时,向上移动一个级别是合乎逻辑的。无论哪种方式都具有相同的输出 - 区别在于,在 `parents()` 中使用 `:first` 可能会有点昂贵,因为 `:first` 是 Sizzle 扩展,并且选择器通常与之前的每个(祖先)元素进行匹配返回。 (4认同)