2015-10-23 42 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()

相關問題