【发布时间】:2010-10-29 13:06:51
【问题描述】:
检测 jQuery 选择器是否返回空对象的最佳方法是什么。 如果你这样做:
alert($('#notAnElement'));
你得到了[object Object],所以我现在的做法是:
alert($('#notAnElement').get(0));
这将写入“未定义”,因此您可以对其进行检查。但这似乎非常糟糕。还有什么办法?
【问题讨论】:
检测 jQuery 选择器是否返回空对象的最佳方法是什么。 如果你这样做:
alert($('#notAnElement'));
你得到了[object Object],所以我现在的做法是:
alert($('#notAnElement').get(0));
这将写入“未定义”,因此您可以对其进行检查。但这似乎非常糟糕。还有什么办法?
【问题讨论】:
我最喜欢用这个小小的便利来扩展 jQuery:
$.fn.exists = function () {
return this.length !== 0;
}
像这样使用:
$("#notAnElement").exists();
比使用长度更明确。
【讨论】:
this 比true 更有帮助。请参阅我移植 Rails 的presence 方法的答案。
this分配给一个变量,我建议changing the return statement to what CSharp有。
if ( $("#anid").length ) {
alert("element(s) found")
}
else {
alert("nothing found")
}
【讨论】:
选择器返回一个 jQuery 对象数组。如果没有找到匹配的元素,则返回一个空数组。您可以查看选择器返回的集合的.length 或查看第一个数组元素是否为'undefined'。
您可以在 IF 语句中使用 any 以下示例,它们都会产生相同的结果。如果选择器找到匹配的元素,则为 true,否则为 false。
$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
【讨论】:
.length,除非代码很热。这当然是最明确的意图。此外,.size() 已被弃用并且已经存在多年(从 1.8 开始)。我只是要编辑您的答案并将其删除,请随时用注释将其添加回来,但它太旧了,我认为最好不要了。
我喜欢做这样的事情:
$.fn.exists = function(){
return this.length > 0 ? this : false;
}
那么你可以这样做:
var firstExistingElement =
$('#iDontExist').exists() || //<-returns false;
$('#iExist').exists() || //<-gets assigned to the variable
$('#iExistAsWell').exists(); //<-never runs
firstExistingElement.doSomething(); //<-executes on #iExist
【讨论】:
TypeError: firstExistingElement.doSomething is not a function。您可以将整个变量分配/测试包装在 if() 中,并且仅在找到元素时才执行某些操作....
我喜欢使用presence,灵感来自Ruby on Rails:
$.fn.presence = function () {
return this.length !== 0 && this;
}
你的例子变成了:
alert($('#notAnElement').presence() || "No object found");
我发现它优于建议的$.fn.exists,因为您仍然可以使用布尔运算符或if,但真实结果更有用。另一个例子:
$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')
【讨论】:
我的偏好,我不知道为什么 jQuery 中还没有这个:
$.fn.orElse = function(elseFunction) {
if (!this.length) {
elseFunction();
}
};
这样使用:
$('#notAnElement').each(function () {
alert("Wrong, it is an element")
}).orElse(function() {
alert("Yup, it's not an element")
});
或者,就像它在 CoffeeScript 中的样子:
$('#notAnElement').each ->
alert "Wrong, it is an element"; return
.orElse ->
alert "Yup, it's not an element"
【讨论】:
这在 JQuery 文档中:
http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/
alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
【讨论】:
默认情况下,您可能希望一直这样做。我一直在努力包装 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 = {
最后但同样重要的是,您可以在此处获取未压缩的 jquery 源代码:http://code.jquery.com/
【讨论】: