if-not condition失败(jQuery)

时间:2014-05-12 22:28:34

标签: jquery conditional-statements

http://jsbin.com/zexix/1/

$(function() {

    if ( !$(".first.last") ) {
      console.log("div with both first and last classes does not exists")
    } else {
      console.log("it exists");
    }

});

我想检查同时包含firstlast类的div是否存在,但检查失败。

3 个答案:

答案 0 :(得分:12)

你需要检查找到的元素数量,因为jQuery在没有找到元素的情况下返回一个空集合(在if语句中计算为真值):

if ( !$(".first.last").length )

我建议明确地对0进行测试,而不是依赖于假值:

if ( $(".first.last").length === 0 )

答案 1 :(得分:0)

有两种方式:

1。检查长度:

if ( !$(".first.last").length ) { // check the length if none returns 0 == false

2。检查可见性:

if ( !$(".first.last").is(':visible') ) { // returns boolean true/false

答案 2 :(得分:0)

您可以通过检查从JQuery返回的第一个对象来简化此操作:

if (!$(".first.last")[0]){
    console.log("div with both first and last classes does not exists");
} else {
  console.log("it exists");
}