使用 jQuery 检查是否有任何祖先有一个类

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

Check if any ancestor has a class using jQuery

javascriptjqueryhtmljquery-selectorsjquery-1.7

提问by crmpicco

Is there any way in jQuery to check if anyparent, grand-parent, great-grand-parent has a class.

jQuery 中是否有任何方法可以检查是否有任何父母、祖父母、曾祖父母有一个类。

I have a markup structure that has left me doing this sort of thing in the code:

我有一个标记结构,让我在代码中做这种事情:

$(elem).parent().parent().parent().parent().hasClass('left')

However, for code readability i'd like to avoid this sort of thing. Is there any way to say "any parent/grandparent/great-grand-parent has this class"?

但是,为了代码可读性,我想避免这种事情。有没有办法说“任何父母/祖父母/曾祖父母都有这门课”?

I am using jQuery 1.7.2.

我正在使用 jQuery 1.7.2。

回答by Alex

if ($elem.parents('.left').length) {

}

回答by A. Wolff

There are many ways to filter for element ancestors.

有很多方法可以过滤元素祖先。

if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/} 

Beware, closest()method includes element itself while checking for selector.

当心closest()方法在检查选择器时包括元素本身。

Alternatively, if you have a unique selectormatching the $elem, e.g #myElem, you can use:

或者,如果您有一个与 匹配的唯一选择器$elem,例如#myElem,您可以使用:

if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}

If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:

如果您只想根据样式目的匹配依赖其任何祖先类的元素,只需使用CSS 规则

.parentClass #myElem { /* CSS property set */ }

回答by Igor Dymov

You can use parentsmethod with specified .classselector and check if any of them matches it:

您可以使用parents具有指定.class选择器的方法并检查它们中是否有任何匹配它:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}