Jak mogę wykryć, że selektor Zwraca wartość null?

Jaki jest najlepszy sposób na wykrycie, czy selektor jQuery zwróci pusty obiekt. Jeśli tak:

alert($('#notAnElement'));

Dostajesz [object Object], więc teraz robię to tak:

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

Który napisze "undefined", więc możesz to sprawdzić. Ale wydaje się bardzo źle. Jaki jest inny sposób?

Author: Ata Iravani, 2009-05-28

7 answers

Moim ulubionym jest rozszerzenie jQuery z tą małą wygodą:

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

Używane jak:

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

Bardziej wyraźne niż użycie długości.

 461
Author: Magnar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-23 05:43:35
if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}
 187
Author: duckyflip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-27 19:26:01

Selektor zwraca tablicę obiektów jQuery. Jeśli nie znaleziono pasujących elementów, zwraca pustą tablicę. Możesz sprawdzić .length kolekcji zwracanej przez selektor lub sprawdzić, czy pierwszy element tablicy jest 'undefined'.

Możesz użyć dowolnego następujących przykładów wewnątrz instrukcji IF i wszystkie one dają ten sam wynik. True, jeśli selektor znalazł pasujący element, false w przeciwnym razie.

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
 58
Author: Jose Basilio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-21 03:14:44

Lubię robić coś takiego:

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

Więc możesz zrobić coś takiego:

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/

 35
Author: CSharp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-02 10:21:56

Lubię używać presence, inspirowanych Ruby on Rails :

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

Twój przykład staje się:

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

Uważam, że jest lepszy od proponowanego $.fn.exists, ponieważ nadal można używać operatorów boolean lub if, ale prawdziwy wynik jest bardziej przydatny. Inny przykład:

$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')
 8
Author: Marc-André Lafortune,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-19 07:49:06

Moje preferencje i nie mam pojęcia dlaczego tego nie ma już w jQuery:

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

Używane w ten sposób:

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

Lub, jak to wygląda w CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"
 7
Author: nilskp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-17 17:05:12

To jest w dokumentacji JQuery:

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

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
 6
Author: Daniel De León,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-13 21:29:54