Javascript 如何在jQuery中找到具有已知类的父级?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5333426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find a parent with a known class in jQuery?
提问by John Smith
I have a <div>
that has many other <div>
s within it, each at a different nesting level. Rather than give every child <div>
an identifier, I rather just give the root <div>
the identifier. Here's an example:
我有一个里面<div>
有很多其他<div>
的,每个都在不同的嵌套级别。与其给每个孩子<div>
一个标识符,我宁愿只给根<div>
标识符。下面是一个例子:
<div class="a" id="a5">
<div class="b">
<div class="c">
<a class="d">
</a>
</div>
</div>
</div>
If I write a function in jQuery to respond to class d
and I want to find the ID for its parent, class a
, how would I do this?
如果我在 jQuery 中编写一个函数来响应 classd
并且我想找到它的父级 class 的 ID,a
我该怎么做?
I cannot simply do $('.a').attr('id');
, because there are multiple class a
s. I could find its parent's parent's parent's ID but that seems of poor design, slow, and not very polymorphic (I would have to write different code for finding the ID for class c
).
我不能简单地做$('.a').attr('id');
,因为有多个类a
。我可以找到它的父母的父母的父母的 ID 但这似乎设计不佳,速度慢,而且不是很多态(我必须编写不同的代码来查找 class 的 ID c
)。
回答by SLaks
Assuming that this
is .d
, you can write
假设this
是这样.d
,你可以写
$(this).closest('.a');
The closest
methodreturns the innermost parent of your element that matches the selector.
该closest
方法返回与选择器匹配的元素的最里面的父元素。
回答by Drew Noakes
回答by Amr Elgarhy
You can use parents()to get all parents with the given selector.
您可以使用parents()获取具有给定选择器的所有父级。
Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
描述:获取当前匹配元素集合中每个元素的祖先,可选地由选择器过滤。
But parent()will get just the first parent of the element.
但是parent()只会得到元素的第一个父元素。
Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
描述:获取当前匹配元素集合中每个元素的父元素,可选地由选择器过滤。
And there is .parentsUntil()which I think will be the best.
还有.parentsUntil()我认为它是最好的。
Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.
描述:获取当前匹配元素集合中每个元素的祖先,直到但不包括选择器匹配的元素。
回答by jai3232
Use .parentsUntil()
使用 .parentsUntil()
$(".d").parentsUntil(".a");
回答by Anjana Silva
Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.
摘自上面@Resord 的评论。这个对我有用,并且更倾向于这个问题。
$(this).parent().closest('.a');
Thanks
谢谢