if-not condition失败(jQuery)

3zz*_*zzy 5 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");
    }

});
Run Code Online (Sandbox Code Playgroud)

我想检查一下这两个firstlast类的div是否都不存在,但是检查失败了.

Dav*_*mas 13

您需要检查找到的元素数量,因为如果没有找到任何元素,jQuery将返回一个空集合(在if语句中计算为truthy值):

if ( !$(".first.last").length )
Run Code Online (Sandbox Code Playgroud)

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

if ( $(".first.last").length === 0 )
Run Code Online (Sandbox Code Playgroud)