jQuery 如何检测选择器是否返回 null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/920236/
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
How can I detect if a selector returns null?
提问by peirix
What is the best way to detect if a jQuery-selector returns an empty object. If you do:
检测 jQuery 选择器是否返回空对象的最佳方法是什么。如果你这样做:
alert($('#notAnElement'));
you get [object Object], so the way I do it now is:
你得到 [object Object],所以我现在的做法是:
alert($('#notAnElement').get(0));
which will write "undefined", and so you can do a check for that. But it seems very bad. What other way is there?
它将写入“未定义”,因此您可以对此进行检查。但这似乎非常糟糕。还有什么办法?
回答by Magnar
My favourite is to extend jQuery with this tiny convenience:
我最喜欢的是用这种微小的便利来扩展 jQuery:
$.fn.exists = function () {
return this.length !== 0;
}
Used like:
像这样使用:
$("#notAnElement").exists();
More explicit than using length.
比使用长度更明确。
回答by duckyflip
if ( $("#anid").length ) {
alert("element(s) found")
}
else {
alert("nothing found")
}
回答by Jose Basilio
The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length
of the collection returned by the selector or check whether the first array element is 'undefined'.
选择器返回一个 jQuery 对象数组。如果没有找到匹配的元素,它返回一个空数组。您可以检查.length
选择器返回的集合的 ,或检查第一个数组元素是否为“未定义”。
You can use anythe following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.
您可以在 IF 语句中使用以下任何示例,它们都会产生相同的结果。如果选择器找到匹配元素,则为真,否则为假。
$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
回答by CSharp
I like to do something like this:
我喜欢做这样的事情:
$.fn.exists = function(){
return this.length > 0 ? this : false;
}
So then you can do something like this:
那么你可以做这样的事情:
var firstExistingElement =
$('#iDontExist').exists() || //<-returns false;
$('#iExist').exists() || //<-gets assigned to the variable
$('#iExistAsWell').exists(); //<-never runs
firstExistingElement.doSomething(); //<-executes on #iExist
回答by Marc-André Lafortune
I like to use presence
, inspired from Ruby on Rails:
我喜欢使用Ruby on Rails 的presence
启发:
$.fn.presence = function () {
return this.length !== 0 && this;
}
Your example becomes:
你的例子变成:
alert($('#notAnElement').presence() || "No object found");
I find it superior to the proposed $.fn.exists
because you can still use boolean operators or if
, but the truthy result is more useful. Another example:
我发现它优于建议的,$.fn.exists
因为您仍然可以使用布尔运算符 or if
,但真实的结果更有用。另一个例子:
$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')
回答by nilskp
My preference, and I have no idea why this isn't already in jQuery:
我的偏好,我不知道为什么这不在 jQuery 中:
$.fn.orElse = function(elseFunction) {
if (!this.length) {
elseFunction();
}
};
Used like this:
像这样使用:
$('#notAnElement').each(function () {
alert("Wrong, it is an element")
}).orElse(function() {
alert("Yup, it's not an element")
});
Or, as it looks in CoffeeScript:
或者,正如它在 CoffeeScript 中的样子:
$('#notAnElement').each ->
alert "Wrong, it is an element"; return
.orElse ->
alert "Yup, it's not an element"
回答by Daniel De León
This is in the JQuery documentation:
这是在 JQuery 文档中:
http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/
http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/
alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
回答by Devin G Rhode
You may want to do this all the time by default. I've been struggling to wrap the jquery function or jquery.fn.init method to do this without error, but you can make a simple change to the jquery source to do this. Included are some surrounding lines you can search for. I recommend searching jquery source for The jQuery object is actually just the init constructor 'enhanced'
默认情况下,您可能希望始终执行此操作。我一直在努力包装 jquery 函数或 jquery.fn.init 方法来做到这一点而不会出错,但是您可以对 jquery 源进行简单的更改来做到这一点。包括一些您可以搜索的周围线路。我建议搜索 jquery 源The jQuery object is actually just the init constructor 'enhanced'
var
version = "3.3.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
var result = new jQuery.fn.init( selector, context );
if ( result.length === 0 ) {
if (window.console && console.warn && context !== 'failsafe') {
if (selector != null) {
console.warn(
new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
);
}
}
}
return result;
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
jQuery.fn = jQuery.prototype = {
Last but not least, you can get the uncompressed jquery source code here: http://code.jquery.com/
最后但并非最不重要的是,您可以在此处获取未压缩的 jquery 源代码:http: //code.jquery.com/