289

检测 jQuery 选择器是否返回空对象的最佳方法是什么。如果你这样做:

alert($('#notAnElement'));

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

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

这将写“未定义”,因此您可以检查一下。但这似乎非常糟糕。还有什么其他方法?

4

8 回答 8

512

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

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

像这样使用:

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

比使用长度更明确。

于 2009-05-28T11:10:02.103 回答
205
if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}
于 2009-05-28T10:51:45.480 回答
74

选择器返回一个 jQuery 对象数组。如果没有找到匹配的元素,则返回一个空数组。您可以检查.length选择器返回的集合或检查第一个数组元素是否为“未定义”。

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

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
于 2009-05-28T11:06:59.897 回答
39

我喜欢做这样的事情:

$.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

http://jsfiddle.net/vhbSG/

于 2012-06-02T10:21:56.970 回答
9

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

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

您的示例变为:

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

我发现它优于建议的$.fn.exists,因为您仍然可以使用布尔运算符 or if,但真实的结果更有用。另一个例子:

$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')
于 2013-02-21T22:44:22.710 回答
7

我的偏好,我不知道为什么这在 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"
于 2012-08-06T20:10:26.183 回答
6

这是在 JQuery 文档中:

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

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
于 2014-05-13T21:29:54.113 回答
0

默认情况下,您可能希望一直这样做。我一直在努力包装 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/

于 2018-11-29T01:27:01.480 回答