为何这段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
相关产品推荐
相关产品推荐

