如何使用jquery获取href属性?

时间:2013-08-03 19:34:08

标签: jquery

<table class="table1">
    <tbody>        
       <tr class="tablerow1"> 
            <td valign="top"> 
              <strong> 
              <a href="http://www.wineweb.com/scripts/wineryPg.cfm/11094/Aan-de-Doorns-Co%2Dop/" target="_top">Aan de Doorns Co-op </a> </strong> </td></tr>
    </tbody>
</table>

这是一个示例html,有多行,其中有多个单元格,实际上是html,这就是我在做什么

$('table.table1').each(function(k, elem) {
                    $(this).find('tr').each(function(j, elem){
                        $(this).find('td').each(function(i,elem){
                            console.log($(this).find('strong a').attr('href'));
                        })
                    })
                });

但我无法通过此方法获得href。

5 个答案:

答案 0 :(得分:4)

您可以使用map方法并避免使用嵌套的$.each语句。

    var hrefs = $('table.table1 tr td a').map(function() {
        return this.href;
    }).get();

   console.log(hrefs.join(','))

<强> Check Fiddle

答案 1 :(得分:2)

$('.table1 strong a').each(function() {
    console.log(this.href);
});

答案 2 :(得分:1)

您可以大大简化代码:

$('table.table1 tr td a').each(function(idx, elem) {
    console.log($(this).attr('href'));
});

答案 3 :(得分:1)

使用find方法(效率更高)。

$('.table1').find('a').each(function() {
    console.log($(this).attr('href'));
}

答案 4 :(得分:0)

你可以像这样在一个标签中添加一个类:

<a class="link" href="your_url" target="_top">Aan de Doorns Co-op </a>

然后在你的jquery片段中使用这个类:

console.log($(this).find('.link').attr('href'));

我为此创造了一个小提琴..希望它能帮助

fiddle here