Javascript 如何使用 hasClass 来检测类是否不是我想要的类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4521660/
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
How do I use hasClass to detect if a class is NOT the class I want?
提问by sehummel
How do I use hasClass so it works as doesNotHaveClass? In other words, rather than looking to see if it is a specified class, looking to see if it is NOT a specified class. Can I use an exclamation point or something like that?
我如何使用 hasClass 使其像 dosNotHaveClass 一样工作?换句话说,与其查看它是否是指定的类,不如查看它是否不是指定的类。我可以使用感叹号或类似的东西吗?
回答by BoltClock
Yes, you can.
是的你可以。
if (!$('element').hasClass('do-not-want')) {
// This element does not have the .do-not-want class
}
回答by Michael Petrov
However if you're trying to use selectors to find all the items that don't have a class, perhaps try this:
但是,如果您尝试使用选择器来查找所有没有类的项目,请尝试以下操作:
// find all divs that don't have "badClass" class
$('div').not('.badClass').each(function(){});
回答by Paul
if (!$('a').hasClass('xyz')){
...
}
回答by Chandu
Yes, you can As per the jQuery documentation:
是的,您可以根据 jQuery 文档:
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are.
如果类被分配给一个元素, .hasClass() 方法将返回 true,即使其他类也是如此。
Since the function returns a boolean you can use exclamation point to negate the result.
由于该函数返回一个布尔值,您可以使用感叹号来否定结果。
回答by user1915816
You can check if the return is false:
您可以检查返回是否为假:
if($(element).hasClass("class") === false) {...}