You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何这段jQuery代码弹出“found it”而非“nope”?

为什么这段jQuery代码总是弹出“found it”?

先看看你给出的代码:

HTML代码

<div class="site-inner"> 
  <div>Another div</div> 
</div> 
<footer class="vc_row">Footer</footer>

jQuery代码

if ( $('.site-inner').find('.vc_row') ) { 
  alert('found it'); 
} else { 
  alert('nope'); 
}

问题的核心在于jQuery的查找方法(比如find())的返回值特性:不管有没有找到匹配的DOM元素,它都会返回一个jQuery对象——哪怕这个对象是空的(里面没有任何元素)。

在JavaScript的if判断里,只有false、0、空字符串""、null、undefined、NaN这些值会被判定为“假”。而空的jQuery对象不属于这些范畴,所以会被当作“真”来处理,自然就触发了alert('found it')。

要得到正确的判断结果,你可以用这两种常用方法:

  • 检查返回对象的length属性:如果找到元素,length会大于0,否则为0(0会被判定为假)
    if ( $('.site-inner').find('.vc_row').length ) { 
      alert('found it'); 
    } else { 
      alert('nope'); 
    }
    
  • 使用is()方法判断是否包含有效元素:is('*')会检查jQuery对象里是否至少有一个元素
    if ( $('.site-inner').find('.vc_row').is('*') ) { 
      alert('found it'); 
    } else { 
      alert('nope'); 
    }
    

内容的提问来源于stack exchange,提问作者Aryadne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:24:13