if-not 条件失败 (jQuery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23619973/
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
if-not condition fails (jQuery)
提问by eozzy
$(function() {
if ( !$(".first.last") ) {
console.log("div with both first and last classes does not exists")
} else {
console.log("it exists");
}
});
I want to check if a div with both first
and last
classes DOES NOT exist, but the check fails.
我想检查一个同时包含first
和last
类的 div 是否不存在,但检查失败。
回答by David says reinstate Monica
You need to check the number of elements found, as jQuery returns an empty collection in the event of no elements being found (which evaluates to a truthy value in the if statement):
您需要检查找到的元素数量,因为 jQuery 在没有找到元素的情况下返回一个空集合(在 if 语句中计算为真值):
if ( !$(".first.last").length )
I'd suggest testing against 0 explicitly, rather than relying on a falsey value, though:
不过,我建议明确针对 0 进行测试,而不是依赖于 falsey 值:
if ( $(".first.last").length === 0 )
回答by Jai
there are two ways:
有两种方法:
1. check the length:
1.检查长度:
if ( !$(".first.last").length ) { // check the length if none returns 0 == false
2. check the visibility:
2.检查可见性:
if ( !$(".first.last").is(':visible') ) { // returns boolean true/false
回答by Susheel Singh
You can simplify this by checking the first object that is returned from JQuery:
您可以通过检查从 JQuery 返回的第一个对象来简化此操作:
if (!$(".first.last")[0]){
console.log("div with both first and last classes does not exists");
} else {
console.log("it exists");
}