判断 jQuery 是否没有找到任何元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2877654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determining whether jQuery has not found any element
提问by Bardock
I'm using jQuery's selectors, especially id selector:
我正在使用 jQuery 的选择器,尤其是 id 选择器:
$("#elementId")...
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]
我应该如何确定 jQuery 是否找到了该元素?即使具有指定 id 的元素不存在,下一个语句也给我:[object Object]
alert($("#idThatDoesnotexist"));
回答by futuraprime
$('#idThatDoesnotexist').length
is what you're looking for. (If it finds nothing, this will === 0
.) So your conditional statement should probably be:
$('#idThatDoesnotexist').length
就是你要找的。(如果它什么也没找到,这会=== 0
。)所以你的条件语句可能应该是:
if($('#id').length) { /* code if found */ } else { /* code if not found */ }
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(几乎)在您使用它时总是返回“jQuery 对象”,它是 jQuery 发现的元素的包装器,允许方法链接。
回答by John Hartsock
Futuraprime is right but you can shorten your syntax by doing the following:
Futuraprime 是对的,但您可以通过执行以下操作来缩短语法:
if ($("#id").length) {
//at least one element was found
} else {
//no elements found
}
回答by Spas
!$.isEmptyObject($.find('#id'))
This will return true if the element exists and false if it doesn't.
如果元素存在,则返回 true,否则返回 false。
回答by Blackjoker
$('#my_selector').length > 0
$('#my_selector').get(0) !== undefined
$('#my_selector')[0] !== undefined
This is the basic, now do whatever you want.
这是基本的,现在做你想做的。