Pregunta

¿Cuál es la mejor manera de detectar si un selector de jQuery devuelve un objeto vacío. Si lo hace:

alert($('#notAnElement'));

se obtiene [object Object], por lo que la forma en que hago ahora es:

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

que escribir "indefinido", y lo que puede hacer un cheque por esa. Pero parece muy malo. ¿Qué otra manera hay?

¿Fue útil?

Solución

Mi favorito es extender jQuery con esta pequeña conveniencia:

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

Se utiliza como:

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

Más explícita que el uso de longitud.

Otros consejos

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

El selector devuelve una matriz de objetos jQuery. Si no se encuentran elementos que coinciden, devuelve una matriz vacía. Puede comprobar el .length de la colección devuelta por el selector o compruebe si el primer elemento de matriz se 'indefinido'.

Puede utilizar cualquier los siguientes ejemplos dentro de una instrucción IF y todos ellos producen el mismo resultado. Es cierto, si el selector encuentra un elemento coincidente, falso en caso contrario.

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

Me gustaría hacer algo como esto:

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

Así que usted puede hacer algo como esto:

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/

Me gusta usar presence, inspirado en Ruby on Rails :

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

Su ejemplo se convierte en:

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

Me resulta superior a la $.fn.exists propuesta, porque todavía se puede utilizar operadores booleanos o if, pero el resultado Truthy es más útil. Otro ejemplo:

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

Mi preferencia, y no tengo ni idea de por qué esto no está ya en jQuery:

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

Se utiliza como esto:

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

O, como se ve en CoffeeScript:

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

Esto es en la documentación de jQuery:

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

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

Es posible que desee hacer esto todo el tiempo por defecto. He estado luchando para envolver la función jQuery o método jquery.fn.init hacer esto sin error, pero se puede hacer un simple cambio en la fuente de jQuery para hacer esto. Incluido son algunas líneas circundantes se pueden buscar. Recomiendo buscar fuente de jQuery para 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 = {

Por último, pero no menos importante, se puede obtener el código fuente jQuery sin comprimir aquí: http://code.jquery.com /

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top