如何在jQuery中找到具有已知类的父类? [英] How to find a parent with a known class in jQuery?

查看:176
本文介绍了如何在jQuery中找到具有已知类的父类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< div> ,其中有许多其他< div> 不同的嵌套级别。而不是给每个孩子< div> 一个标识符,我只是给根< div> 标识符。以下是一个例子:

 < div class =aid =a5> 
< div class =b>
< div class =c>
< a class =d>
< / a>
< / div>
< / div>
< / div>

如果我在jQuery中编写函数来响应类 d ,我想为它的父类class a 找到它的ID,我该如何做?我不能简单地做 $('。a')。attr('id'); 因为有多个类 a 秒。我可以找到它的父母的父母的ID,但似乎设计不好,速度慢,而且不是很多形(我必须编写不同的代码来找到类 c 的I​​D) 。

解决方案

假设这个。你可以编写

  $(this).closest('。a'); 

最接近方法返回与选择器匹配的元素的最内层父元素。


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 as. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆