This is the case: I have multiple <span>
tags with the class .productLink
, with a link (<a>
) containing a link to a page.
Example
<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>
Now I would like to retrieve these links with jQuery.
I tried:
$('.productLink').each(function(index){
console.log($(this + ' a').attr('href'));
});
But it threw:
Uncaught Syntax error, unrecognized expression: [object HTMLSpanElement]
我需要改变什么?
答案 0 :(得分:2)
您必须在jquery选择器中选择锚标记,如下所示:
$('.productLink > a').each(function(index){
console.log($(this ).attr('href'));
});
试试here
答案 1 :(得分:1)
您的语法不正确,$(this + ' a')
语句中的this
引用了DOM元素,因此它给出了错误。
由于anchor
是productlink
的孩子,您可以使用该方法中的任何一种来遍历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'));
答案 2 :(得分:0)
console.log('start');
$('.productLink').each(function(index){
var a = $(this).find('a')
console.log(a.attr('href'));
});
您需要在范围内找到锚标记,因此在获取锚标记后使用.find()
使用.attr()