我不太确定如何处理像这样的多个实例。我知道在正常的JS我可以简单地使用[0]等。如何在jQuery中处理单个类的多个实例?
我的代码是这样的:
location.href = $('a.test').attr('href');
我需要处理两个测试的第一个实例和第二。有一个简单的
location.href = $('a.test')[0].attr('href');
我丢失或这样?
我不太确定如何处理像这样的多个实例。我知道在正常的JS我可以简单地使用[0]等。如何在jQuery中处理单个类的多个实例?
我的代码是这样的:
location.href = $('a.test').attr('href');
我需要处理两个测试的第一个实例和第二。有一个简单的
location.href = $('a.test')[0].attr('href');
我丢失或这样?
$('a.test')[0]
回报不具备的方法attr()
DOM元素引用,所以你的脚本将失败
使用.EQ(指数)
location.href = $('a.test').eq(0).attr('href');
或
location.href = $('a.test:eq(0)').attr('href');
这个演示可以帮助:工作演示http://jsfiddle.net/CmQGu/
你也可以使用nth-child
API演示在这里:http://jsfiddle.net/wYdyJ/
有您能接近这一点,就像我给你演示中的许多方面。此外,如果你热衷阅读:Difference between .eq() and .get() and :nth-child()?
API:
first
:http://api.jquery.com/first/(所有偷看了已经错过了这一点)eq
:http://api.jquery.com/eq/nth-child
:http://api.jquery.com/nth-child-selector/代码:
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'));
希望它可以帮助:)
+ 1可以使用'first'以及参见下文':)' –