Jquery 与 .hasClass() 相对?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8961428/
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
Jquery opposite of .hasClass()?
提问by Marc
I am using hasClass() to verify in my if statement if an element has a given class. How can i check in my if statement if an element hasn't a given class? Thank you in advance for your replies. Cheers. Marc.
我正在使用 hasClass() 在我的 if 语句中验证元素是否具有给定的类。如果元素没有给定的类,我如何检查我的 if 语句?预先感谢您的回复。干杯。马克。
回答by James McLaughlin
Why not simply:
为什么不简单:
if (!el.hasClass ('foo'))
{
}
回答by Didier Ghys
More generally in javascript, to check the opposite of a boolean result, use the logical NOT operator !
:
更一般地,在 javascript 中,要检查布尔结果的反面,请使用逻辑 NOT 运算符!
:
var isValid = false;
if (!isValid) {
// execute if isValid = false;
}
For your question, .hasClass()
returns a boolean if the element has the specified class, so if you have the expression:
对于您的问题,.hasClass()
如果元素具有指定的类,则返回一个布尔值,因此如果您有表达式:
<div class="someClass"></div>
if ($('div').hasClass('someClass')) {
// will execute
}
to check if it does not have that class:
检查它是否没有该类:
if (!$('div').hasClass('someClass')) {
// will not get here because our element has the class "someClass"
}
When selecting elements, if you want to avoid those who have a certain class, you can use the :not()
pseudo-selector:
选择元素的时候,如果想避开那些有一定类的元素,可以使用:not()
伪选择器:
$('div:not(.someClass)')
回答by fivedigit
if (!element.hasClass('classname')) {
...
}
回答by user4174014
You can use
您可以使用
el.is('.oneClass:not(.secondClass)')
if you need check more than one class or
如果您需要检查多个课程或
el.is(':not(.secondClass)')
if you need check only one class.
如果你只需要检查一个类。
回答by Sebin Simon
if (!($('class/id/objct').hasClass('class name'))) {
//codes here...
}
回答by DanSolo
To use chaning, you can use the filter.
要使用 chaning,您可以使用过滤器。
$(...some selector...).filter(function (){
return !$(this).hasClass('yourclass');
}).each-or-do-more