2011-12-27 26 views
13

Tengo algunas filas de la tablaObtener atributo href en jQuery

<tr class="b_row"> 
    <td> 
     <div class="cpt"> 
      <h2> 
       <a href="/ref/ref/1.html">example</a> 
      </h2> 
     </div> 
    </td> 
</tr> 

<!--more elements --> 

<tr class="b_row"> 
    <td> 
     <div class="cpt"> 
      <h2> 
       <a href="/ref/two/23.html">example N</a> 
      </h2> 
     </div> 
    </td> 
</tr> 

que necesitan para obtener hipervínculos en el atributo. Yo uso este script

function openAll() 
{ 
    $("tr.b_row").each(function(){ 
    var a_href = $('div.cpt').find('h2 a').attr('href'); 
    alert ("Href is: " + a_href); 
} 

Problema: a_href variables siempre es/ref/ref/1.html

Respuesta

41

En lazo que debe referirse al elemento procceded actual, por lo que escribir:

var a_href = $(this).find('div.cpt h2 a').attr('href'); 
5
var a_href = $('div.cpt').find('h2 a').attr('href'); 

debería ser

var a_href = $(this).find('div.cpt').find('h2 a').attr('href'); 

En la primera línea, su consulta busca todo el documento. En el segundo, la consulta comienza desde su elemento tr y solo obtiene el elemento debajo de ella. (Se pueden combinar los find s si se quiere, me fui separados para ilustrar el punto.)

1

añadir una referencia a this, que se refiere a su b_row:

$("tr.b_row").each(function(){ 
    var a_href = $(this).find('div.cpt h2 a').attr('href'); 
    alert ("Href is: "+a_href); 
}); 
0

Uso $(this) para obtener el deseo elemento.

function openAll() 
{ 
    $("tr.b_row").each(function(){ 
     var a_href = $(this).find('.cpt h2 a').attr('href'); 
     alert ("Href is: "+a_href); 
    }); 
} 
Cuestiones relacionadas