Verifica il risultato della selezione jQuery vuoto


87

Dì lo voglio

var s = $('#something');

e poi voglio testare se jQuery ha trovato # qualcosa, cioè voglio verificare se sè vuoto.

Potrei usare il mio fidato isempty()su di esso:

function isempty(o) {
    for ( var i in o )
        return false;
    return true;
}

O poiché gli oggetti jQuery sono array, suppongo di poterli testare s.length.

Ma nessuno dei due sembra abbastanza nell'idioma di jQuery, non molto jQueryesque. Cosa suggerisci?



inkedmn, sì, domanda simile ma non ho visto la .size()risposta lì, che piuttosto mi piace.


Risposte:



5
if($("#something").length > 0 ){
     // Element found
}
else{
    // No element found
}

-1

Una soluzione ancora più jQueryesque per me è:

jQuery.fn.isEmpty = function(fun){ if (this.length === 0) { fun(); } return this; };

Questo mi consente di scrivere in modo tipico:

$("#sel").fadeOut(500,afterFade).isEmpty(insteadOfFade);
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.