2012-09-27 147 views
12

¿Cómo puedo verificar si existe un Id de atributo en jQuery?Comprobar si el atributo ('id') existe en jQuery

Busqué y encontraron que esto debería funcionar:

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

} 

todavía me sale este error: TypeError: gauge1 objeto no tiene un método 'attr'

+0

¿Qué versión de jQuery está usando? – madth3

+0

Solo ... pruébalo. Si es una cadena vacía, entonces ahí tienes. – Blazemonger

+0

Estoy usando la versión 1.7.2 – CodeMan5000

Respuesta

19

Esta misma funcionará:

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

Compruebe jsfiddle existente en el problema: http://jsfiddle.net/rwaldron/wVqvr/4/

+0

@Blazemonger Acabo de actualizar mi respuesta –

+0

intenté esto pero obtengo TypeError: Object [object Object] no tiene el método 'hasAttr' – CodeMan5000

+0

@LarryBargers Acabo de actualizar mi respuesta, compruébalo –

9

J UST tratar de la manera antigua

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

usted podría también sólo tiene que utilizar el js llano objeto

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

'$ (this) [0]' parece más pesado de lo necesario ... –

+0

@destroy - sí, es temprano. 'this' ya es un objeto js simple. Editaré el cambio. –

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 violín: http://jsfiddle.net/NEVYT/

2

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

Cuestiones relacionadas