简体   繁体   English

找到选择器的第一个父级

[英]Find the first parent of a selector

Consider this sample html 考虑这个示例html

<div class="A">
    <div class="B">
        <span class="C">Sample text</span>
        <div class="D">
            <div class="E">Clickable Text</div>
        </div>
    </div>
</div>

And some jQuery 还有一些jQuery

$(".E").click(function(){
    //body
});

What is the easiest way to get a parent of $(this) that matches a selector? 获取与选择器匹配的$(this)父级的最简单方法是什么? For example, say in the example I need to get the div where class="A" . 例如,在示例中我需要获取div class="A"的div。 At the moment because I know the structure of the html I could do 目前因为我知道我能做的html的结构

$(this).parent().parent();

But I'm looking for a way that would work regardless of the structure. 但我正在寻找一种无论结构如何都能工作的方法。 Something along the lines of 有点像

$(this).findFirstParent(".A");

I hope I've been understandable. 我希望我能理解。

$(".E").click(function(){
    console.log($(this).closest('.A'));
    /* console.log($(this).parents('.A')); works fine too */
});

See 看到
http://api.jquery.com/closest/ http://api.jquery.com/closest/
http://api.jquery.com/parents/ http://api.jquery.com/parents/

Note that parent() is different than parents() method (the first one look for one ancestor only) 请注意, parent()parents()方法不同(第一个只查找一个祖先)

First Solution: 第一解决方案

$(this).closest('.A')

Source: http://api.jquery.com/closest/ This will return the first parent when traversing that matchs the selector. 来源: http//api.jquery.com/closest/这将在遍历匹配选择器时返回第一个父级。

Second solution: 二解决方案:

$(this).parents('.A:first')

Source: http://api.jquery.com/parents/ This will return all the parents that matches the selectors 来源: http//api.jquery.com/parents/这将返回与选择器匹配的所有父项

关于什么

$(this).closest(".A");

这就是我这样做的方式

$(this).parents("div.A")

The jQuery parent selector might help you there. jQuery父选择器可以帮助你。 You can combine it with the class you are looking for. 您可以将它与您要查找的课程相结合。 See the docs @ http://api.jquery.com/parent-selector/ 请参阅docs @ http://api.jquery.com/parent-selector/

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

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