2015-10-23 46 views
0

这种情况下:我有多个<span>标签与类.productLink,与链接(<a>)包含一个页面的链接。如何通过jQuery在<span>中获取<a>中的href标记?

<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这些链接。

我尝试:

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

但它投掷:

未捕获的语法错误,不能识别的表达式:[对象HTMLSpanElement]


See live fiddle

我必须改变什么?

回答

2

它的href您要选择里面的锚标记像这样的jquery选择器:

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

试试看here

1

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

由于anchorproductlink的孩子,你可以使用该方法来遍历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')); 
+0

我错过了一些东西吗? – Satpal

+3

有时会出现不适当的投票结果,而这种情况发生在我身上。 – guradio

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

DEMO

你需要找到的跨度内的锚标记,以便使用.find()获得锚标记后得到使用.attr()

相关问题