jQuery 找到最近的具有某个类的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19865647/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:43:57  来源:igfitidea点击:

Find closest div that has a certain class

javascriptjquery

提问by user765368

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 requiredand another_class. Therefore something like this:

如何找到具有类的复选框的父 div required?正如你在上面看到的,div 有两个类requiredanother_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.

但这也行不通。

回答by Karl-André Gagnon

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

您可以在 中使用 CSS 选择器.closest(),就像这样:

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

回答by Pratik Goenka

Alternatively you can also use

或者,您也可以使用

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