如何使用 jQuery 在 <span> 中获取 <a> 中的 href 标签?

How to get href tag in <a> in <span> with jQuery?

情况是这样的:我有多个带有 class .productLink<span> 标签,其中 link (<a>) 包含一个 link 到一个页面。

例子

<span class="productLink">
    <a href="/Products/Category/item.html">A very nice product</a>
</span>
<span class="productLink">
    <a href="/Products/Category/otheritem.html">Also very nice product</a>
</span>

现在我想用 jQuery 检索这些 link。

我试过了:

$('.productLink').each(function(index){
    console.log($(this + ' a').attr('href'));
});

但它抛出了:

Uncaught Syntax error, unrecognized expression: [object HTMLSpanElement]


See live fiddle

我需要更改什么?

您的语法不正确,语句 this 中的 $(this + ' a') 引用 DOM 元素,因此给出了错误。

因为anchorproductlink的child你可以使用任何一种方法遍历到anchor然后可以得到它的href属性。

//Using context selector
console.log($('a', this).attr('href'));

//Using find method
console.log($(this).find('a').attr('href'));

//Using children method
console.log($(this).children('a').attr('href'));
console.log('start');
$('.productLink').each(function(index){
    var a = $(this).find('a')
    console.log(a.attr('href'));
});

DEMO

您需要在 span 内找到锚标记,因此在获取锚标记后使用 .find() 使用 .attr()

获取其 href

您必须 select jquery 内的锚标记 select 或者像这样:

$('.productLink > a').each(function(index){
    console.log($(this ).attr('href'));
});

试一试here