找到具有特定類的最近div

[英]Find closest div that has a certain class


Let's say that I have some HTML like this:

假設我有一些像這樣的HTML:

<div>
    <div class="required another_class">
        <div class="some_class">
            <input type="checkbox" name="some_check" value="" />
        </div>
    </div>
</div>

How do I find the parent div of the checkbox that has the class required? As you can see above, the div has two classes required and another_class. Therefore something like this:

如何找到具有所需類的復選框的父div?如上所示,div有兩個必需的類和another_class。因此這樣的事情:

$(':checkbox').closest('div[class=required]');

Will not work. I thought I could do something like:

不管用。我以為我可以這樣做:

$(':checkbox').closest('div').hasClass('required');

But that doesn't work either.

但這也不起作用。

2 个解决方案

#1


15  

You can use CSS selector in .closest(), just like that :

您可以在.closest()中使用CSS選擇器,就像這樣:

$(':checkbox').closest('div.required');

#2


0  

Alternatively you can also use

或者你也可以使用

$(':checkbox').parents('div.required')

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/11/08/7250e0e2e17063275280fb506fa503c9.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com