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

查看:16
本文介绍了如何在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 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天全站免登陆