[英]How to handle multiple instances of a single class in jQuery?
我不确定如何处理这样的多个实例。 我知道在普通的JS中,我可以简单地使用[0]等。
我的代码是这样的:
location.href = $('a.test').attr('href');
我需要同时处理第一个实例和第二个实例。 有一个简单的
location.href = $('a.test')[0].attr('href');
我想念还是这样?
$('a.test')[0]
返回一个不带attr()
方法的dom元素引用,因此您的脚本将失败
使用.eq(index)
location.href = $('a.test').eq(0).attr('href');
要么
location.href = $('a.test:eq(0)').attr('href');
您尝试在JavaScript DOM对象上调用attr而不是使用jQuery对象,因为索引器返回DOM对象使用eq()获取jQuery对象
location.href = $('a.test').eq(0).attr('href');
您可以使用带有href而不是attr的DOM对象
location.href = $('a.test')[0].href;
该演示可能会有所帮助: 正在运行演示 http://jsfiddle.net/CmQGu/
您还可以在此处使用nth-child
api演示: http : //jsfiddle.net/wYdyJ/
有很多方法可以解决此问题,就像我在演示中向您展示的那样。 也如果您热衷于阅读: .eq()和.get()和: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'));
希望对您有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.