289

jQuery-selectorが空のオブジェクトを返すかどうかを検出するための最良の方法は何ですか。もし、するなら:

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ステートメント内で次の例を使用する、すべて同じ結果が得られます。セレクターが一致する要素を見つけた場合はTrue、それ以外の場合はFalse。

$('#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

私はRubyonRailspresenceからインスピレーションを得て使用するのが好きです:

$.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('...')
于 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 に答える