如何使用jQuery获取href属性?

3
<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,实际上有多行多列的单元格。这就是我所做的。

$('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。

本来想要请求 HTML,但是它已经被上传了。我建议把这个放到一个查询中。 - kikuchiyo
1
似乎它正在工作 http://jsfiddle.net/wCAWT/ - Sachin
你的代码在Waterfox上运行良好。$('table.table1').each(function(){console.log($(this).find('tr>td>strong>a').attr('href'));}); - Mr. Polywhirl
5个回答

4
你可以使用map方法避免嵌套的$.each语句。
    var hrefs = $('table.table1 tr td a').map(function() {
        return this.href;
    }).get();

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

查看代码示例


你是用 .get(); 做什么的? - nirazul
Map返回一个包含在jQuery包装器中的数组。为了将其转换为普通数组,我们使用get() - Sushanth --
我在你的fiddle上试了一下,看起来结果完全相同。 - nirazul

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

1
$(this).attr('href') -> this.href - mishik
'.table1 strong a',以防万一。 - Meryovi

1
你可以大幅简化你的代码:
```html

你可以大幅简化你的代码:

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

我知道,我知道。我希望能够被提醒这些参数,因为我经常会在后面用到它们 ;)。 - nirazul

1
使用 find 方法(更有效率)。
$('.table1').find('a').each(function() {
    console.log($(this).attr('href'));
}

0

你可以像这样为a标签添加一个类:

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

然后在你的 jQuery 代码片段中使用这个类,像这样:

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

我为此创建了一个示例,希望能有所帮助

这里是示例链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接