Kaip patikrinti elemento egzistavimą jQuery?
Dabartinis mano kodas yra toks:
if ($(selector).length > 0) {
// Do something
}
Ar yra elegantiškesnis būdas tai padaryti? Galbūt įskiepiu arba funkcija?
Taip!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
Tai yra atsakymas į: Herding Code podcast with Jeff Atwood
Jei naudojote
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
jūs reikštumėte, kad grandininis jungimas yra įmanomas, nors taip nėra.
Taip būtų geriau:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
Arba iš DUK:
if ( $('#myDiv').length ) { /* Do something */ }
Taip pat galite naudoti šį variantą. Jei jQuery objektų masyve nėra reikšmių, tuomet, gavus pirmąjį masyvo elementą, būtų grąžinama neapibrėžta reikšmė.
if ( $('#myDiv')[0] ) { /* Do something */ }