2013-10-05 44 views
0

我不太確定如何處理像這樣的多個實例。我知道在正常的JS我可以簡單地使用[0]等。如何在jQuery中處理單個類的多個實例?

我的代碼是這樣的:

location.href = $('a.test').attr('href'); 

我需要處理兩個測試的第一個實例和第二。有一個簡單的

location.href = $('a.test')[0].attr('href'); 

我丟失或這樣?

回答

2

$('a.test')[0]回報不具備的方法attr() DOM元素引用,所以你的腳本將失敗

使用.EQ(指數)

location.href = $('a.test').eq(0).attr('href'); 

location.href = $('a.test:eq(0)').attr('href'); 
+0

+ 1可以使用'first'以及參見下文':)' –

2

你是試圖在javascript DOM對象上調用attr而不是使用jQuery對象作爲索引器返回DOM對象使用eq()來獲取jQuery ob JECT

location.href = $('a.test').eq(0).attr('href'); 

您可以使用DOM對象與HREF代替ATTR

location.href = $('a.test')[0].href; 
+0

+ 1喲,很高興見到你身邊!再次錯過了'。第一個':P –

+0

謝謝@Tats_innit,這裏也一樣。我留給你:) – Adil

+0

哈哈歡呼,我還加了'第n個孩子',很高興見到你很久以後的煩惱! ':)' –

2
location.href = $('a.test').eq(0).attr('href'); 

,或者你可以嘗試

location.href = $('a.test:eq(0)').attr('href'); 

參考eq():eq()attr

+0

+1給你以及':)' –

1

這個演示可以幫助:工作演示http://jsfiddle.net/CmQGu/

你也可以使用nth-child API演示在這裏:http://jsfiddle.net/wYdyJ/

有您能接近這一點,就像我給你演示中的許多方面。此外,如果你熱衷閱讀:Difference between .eq() and .get() and :nth-child()?

API:

代碼

alert(location.href = $('a.test').eq(0).attr('href')); 

alert(location.href = $('a.test').first().attr('href')); 

alert(location.href = $('a.test:nth-child(2)').attr('href')); 

希望它可以幫助:)

相關問題