确定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屋!