2013-10-05 43 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')); 

希望它可以帮助:)

相关问题