Javascript 测试空的 jQuery 选择结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2649346/
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
Test for empty jQuery selection result
提问by Billiam
Say I do
说我同意
var s = $('#something');
and next I want to test if jQuery found #something, i.e. I want to test if sis empty.
接下来我想测试jQuery是否找到#something,即我想测试是否s为空。
I could use my trusty isempty()on it:
我可以使用我的信任isempty():
function isempty(o) {
for ( var i in o )
return false;
return true;
}
Or since jQuery objects are arrays, I suppose I could test s.length.
或者因为 jQuery 对象是数组,我想我可以测试s.length.
But neither seem quite in the idiom of jQuery, not very jQueryesque. What do you suggest?
但两者都不太符合 jQuery 的习惯用法,也不是很 jQueryesque。你有什么建议?
回答by Billiam
Use the s.length property.
使用 s.length 属性。
if(s.length == 0) {
...
}
[edit] size() deprecated in jquery 1.8 http://api.jquery.com/size/
[编辑] size() 在 jquery 1.8 http://api.jquery.com/size/ 中被弃用
回答by Malik Khalil
if($("#something").length > 0 ){
// Element found
}
else{
// No element found
}
回答by Don
An even more jQueryesque solution for me is:
对我来说,一个更加 jQueryesque 的解决方案是:
jQuery.fn.isEmpty = function(fun){ if (this.length === 0) { fun(); } return this; };
This lets me write in typical fashion:
这让我可以用典型的方式写:
$("#sel").fadeOut(500,afterFade).isEmpty(insteadOfFade);

