【问题标题】:if-not condition fails (jQuery) [duplicate]if-not 条件失败(jQuery)[重复]
【发布时间】:2014-06-30 11:04:30
【问题描述】:

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 是否不存在,但检查失败。

【问题讨论】:

    标签: jquery conditional-statements


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 啊,在这里工作到深夜(凌晨 3 点)会犯一些愚蠢的错误。
    • 发生在我们所有人身上。 :)
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      有两种方式:

      1。检查长度:

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

      2。检查可见性:

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

      【讨论】:

        猜你喜欢
        • 2015-12-29
        • 2017-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-15
        • 1970-01-01
        • 2019-04-15
        相关资源
        最近更新 更多