2012-09-27 31 views
12

Come posso verificare se esiste un ID di attributo in jQuery?Verifica se l'attributo ('id') esiste in jQuery

ho cercato in giro e ha scoperto che questo dovrebbe funzionare:

if ($(this).attr('id').attr('id')) 
{ 

} 

ho ancora ottenere questo errore: TypeError: Oggetto gauge1 non ha un metodo 'attr'

+0

Quale versione jQuery stai usando? – madth3

+0

Solo ... testalo. Se è una stringa vuota, allora vai. – Blazemonger

+0

Sto usando la versione 1.7.2 – CodeMan5000

risposta

19

Ciò si lavorerà:

if($(this).attr("id")) 

Controllare esistente jsfiddle sul tema: http://jsfiddle.net/rwaldron/wVqvr/4/

+0

@Blazemonger Ho appena aggiornato la mia risposta –

+0

provato, ma ottengo TypeError: Object [oggetto Object] non ha metodo 'hasAttr' – CodeMan5000

+0

@LarryBargers Ho appena aggiornato la mia risposta, dai un'occhiata –

9

J Ust provare il vecchio modo

if (this.id) { 
    //do something 
} 
0

si potrebbe anche semplicemente usare i js pianura oggetto

if(this.id !== undefined && this.id.length > 0){ 
//todo: use id 
} 
+0

'$ (questo) [0]' sembra più pesante del necessario ... –

+0

@destroy - sì, è presto. 'this' è già un oggetto js semplice. Modificherò la modifica. –

0

HTML:

<div class="hey"></div> 
<div class="you" id="woah"></div> 
<div id="results"></div>​ 

jQuery:

var id = $('div.hey').attr('id'); 
if (id) { 
    // Have an id. 
} else { 
    // Don't have an id. 
} 

un violino: http://jsfiddle.net/NEVYT/

2

if ($(this).attr('id')){ alert(id); }