Domanda

Qual è il modo migliore per rilevare se un selettore jQuery restituisce un oggetto vuoto. Se lo fai:

alert($('#notAnElement'));

si ottiene [object Object], in modo che il mio modo di farlo ora è:

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

, che scriverà "indefinito", e così si può fare un controllo per questo. Ma sembra molto male. Quale altro modo è lì?

È stato utile?

Soluzione

Il mio preferito è quello di estendere jQuery con questo piccolo vantaggio:

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

Utilizzato come:

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

Più esplicito rispetto all'utilizzo di lunghezza.

Altri suggerimenti

if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}

Il selettore restituisce un array di oggetti jQuery. Se non vengono trovati elementi corrispondente, restituisce un array vuoto. È possibile controllare la .length della collezione restituito dal selettore o verificare se il primo elemento dell'array viene 'indefinito'.

È possibile utilizzare qualsiasi i seguenti esempi all'interno di un'istruzione IF e tutti producono lo stesso risultato. Vero, se il selettore trovato un elemento corrispondente, altrimenti false.

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

mi piace fare qualcosa di simile:

$.fn.exists = function(){
    return this.length > 0 ? this : false;
}

Quindi, allora si può fare qualcosa di simile:

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/

Mi piace usare presence, ispirato da Ruby on Rails :

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

Il vostro esempio diventa:

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

Trovo superiore al $.fn.exists proposta perché è ancora possibile utilizzare gli operatori booleani o if, ma il risultato truthy è più utile. Un altro esempio:

$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')

La mia preferenza, e non ho idea del perché questo non è già in jQuery:

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

Utilizzato in questo modo:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

O, come appare nelle CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

Questo è nella documentazione JQuery:

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

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );

Si consiglia di fare questo tutto il tempo per impostazione predefinita. Sto lottando per avvolgere la funzione jquery o il metodo jquery.fn.init per fare questo senza errori, ma si può fare una semplice modifica alla fonte jQuery per fare questo. Incluso sono alcune linee circostanti è possibile cercare. Mi consiglia di ricerca fonte jQuery per 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 = {

Ultimo ma non meno importante, è possibile ottenere il codice sorgente jquery non compresso qui: http://code.jquery.com /

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top