判断jQuery是否没有找到任何元素 [英] Determining whether jQuery has not found any element
问题描述
我正在使用 jQuery 的选择器,尤其是 id 选择器:
I'm using jQuery's selectors, especially id selector:
$("#elementId")...
我应该如何判断 jQuery 是否找到了该元素?即使具有指定 id 的元素不存在,下一条语句给我:[object Object]
How should I determine whether jQuery has found the element or not?
Even If the element with the specified id doesn't exist the next statement give me: [object Object]
alert($("#idThatDoesnotexist"));
推荐答案
$('#idThatDoesnotexist').length
就是你要找的.(如果什么都没找到,这将 === 0
.)所以你的条件语句应该是:
$('#idThatDoesnotexist').length
is what you're looking for. (If it finds nothing, this will === 0
.) So your conditional statement should probably be:
if($('#id').length) { /* code if found */ } else { /* code if not found */ }
您会从该警报返回一个对象,因为 jQuery(几乎)在您使用它时总是返回jQuery 对象",它是 jQuery 发现的允许方法链接的元素的包装器.
You're getting an object returned from that alert because jQuery (almost) always returns the "jQuery object" when you use it, which is a wrapper for the elements jQuery's found that permits method chaining.
这篇关于判断jQuery是否没有找到任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!