检测jquery选择器是否返回空对象的最佳方法是什么? 如果你有:

alert($('#notAnElement'));

你得到[object object],所以我现在做的方式是:

alert($('#notAnElement').get(0));

它会写"undefined"你可以检查一下。但这似乎很糟糕。还有别的办法吗?


当前回答

我最喜欢的是用这个小小的便利来扩展jQuery:

$.fn.exists = function () {
    return this.length !== 0;
}

使用:

$("#notAnElement").exists();

比使用长度更明确。

其他回答

我喜欢使用presence,灵感来自Ruby on Rails:

$.fn.presence = function () {
    return this.length !== 0 && this;
}

你的例子是:

alert($('#notAnElement').presence() || "No object found");

我发现它优于提议的$.fn。存在,因为您仍然可以使用布尔运算符或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对象数组。如果没有找到匹配的元素,则返回一个空数组。您可以检查选择器返回的集合的.length,或者检查第一个数组元素是否'undefined'。

您可以在IF语句中使用以下任何示例,它们都产生相同的结果。如果选择器找到匹配的元素,则为True,否则为false。

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined

这是在JQuery文档中:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}