2013-07-09 79 views
-5

我想要在jQuery中獲取具有特定類的所有<a>標記的name屬性。我該怎麼做。獲取某個類的所有錨的某些屬性

說這是我的HTML:

<div> 
    <a href="#" name="first" class="myClass">Something</a> 
</div> 
<a href="#" name="second">Something else</a> 
<a href="#" name="third" class="myClass">Something else again</a> 

所以我需要得到「第一」和「第三」,因爲他們有類myClass。 「第三」主播沒有這個類,所以我不需要它。

+2

別的所有ATTR名先生:p –

+0

你試過了什麼? – Antguider

+0

@ sambit.albus,我改變了你的問題,所以你更清楚你在問什麼。請考慮你的問題將如何看待SO的其他訪問者。包含代碼總是很好的,並陳述你已經嘗試過的東西。此外,請確保您的標題與問題相對應(即您未提及您想要訪問屬性的事實)。 – Peter

回答

2

使用類選擇.prop()獲取屬性.. attr()如果您正在使用舊版本的jQuery(jQuery的前1.6)的 試試這個...

多個元素

$('.className').each(function(){ 
    console.log($(this).prop('name')) 
}); 

OR使用map()

var nameArray= $('.class').map(function(){ 
    return this.name; 
}).get(); 

console.log(nameArray); //nameArray is an array with all the names 

fiddle usign map

例子..

<a name="test" class="class">test</a> 

alert($('.class').prop('name')); 
+0

謝謝@bipen我如何訪問多個值。它會返回一個數組嗎? –

+0

更新請檢查... :) – bipen

+0

感謝好友它像一個魅力 –

1

試試這個Working Demo

$('div.divClass').children('a.anchorClass').each(function(index) { 
    alert($(this).prop('name')); 
}); 
0
var array = new Array();  

$('a.className').each(function(){ 
    array.push($(this).prop('name')); 
}) 

迭代陣列來獲得的一個標籤

相關問題