如何在jQuery中找到具有已知类的父级? [英] How to find a parent with a known class in jQuery?
问题描述
我有一个
,每个都位于不同的嵌套级别.与其给每个孩子 一个标识符,不如给根 一个标识符.举个例子:<div class="b"><div class="c"><a class="d"></a>
如果我在 jQuery 中编写一个函数来响应 d
类,并且我想找到它的父类 a
的 ID,我该怎么做?
我不能简单地做$('.a').attr('id');
,因为有多个类a
.我可以找到它的父级的父级的 ID,但这看起来设计很差,速度很慢,而且不是很多态(我必须编写不同的代码来查找 c
类的 ID).
解决方案假设this
为.d
,则可以写
$(this).closest('.a');
closest
方法 返回与选择器.
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 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?
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
).
解决方案 Assuming that this
is .d
, you can write
$(this).closest('.a');
The closest
method returns the innermost parent of your element that matches the selector.
这篇关于如何在jQuery中找到具有已知类的父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文