javascript 如何检查类是否不存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14759468/
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 can I check if a class doesn't exist?
提问by dezman
I don't know why this doesn't work, I'm just trying to check if .searchBar
doesn't exist.
我不知道为什么这不起作用,我只是想检查是否.searchBar
不存在。
var $school = "Washington";
if(!$('.searchBar')){
$('#schoolname').text($school);
}
回答by aquinas
if($('.searchBar').length === 0){
Remember, jquery always returns a wrapped set of matching elements. The list may be zero though.
请记住,jquery 总是返回一组包装好的匹配元素。尽管该列表可能为零。
回答by Selvakumar Arumugam
Use .length
to find if it exist if(!$('.searchBar').length){
使用.length
发现,如果它存在if(!$('.searchBar').length){
jQuery $()
function always return a jQuery object even if doesn't find any element. So you need to use .length
property of the jQuery object to find if the element actually exist.
$()
即使没有找到任何元素,jQuery函数也总是返回一个 jQuery 对象。因此,您需要使用.length
jQuery 对象的属性来查找元素是否实际存在。