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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:30:31  来源:igfitidea点击:

How can I check if a class doesn't exist?

javascriptjquery

提问by dezman

I don't know why this doesn't work, I'm just trying to check if .searchBardoesn'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 .lengthto 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 .lengthproperty of the jQuery object to find if the element actually exist.

$()即使没有找到任何元素,jQuery函数也总是返回一个 jQuery 对象。因此,您需要使用.lengthjQuery 对象的属性来查找元素是否实际存在。