在jQuery中选择多个元素不起作用

时间:2014-06-15 09:16:34

标签: javascript jquery jquery-selectors

目前,我有这个jQuery代码:

jQuery("#slideshow article").removeClass("current").removeAttr("class").eq(idx).addClass("current");
jQuery("#slideshow nav a").removeClass("current").removeAttr("class").eq(idx).addClass("current");

正如你所看到的,除了选择器之外,它们完全相同。我试图将它们结合起来:

jQuery("#slideshow article, #slideshow nav a").removeClass("current").removeAttr("class").eq(idx).addClass("current");

(仅选择第一个选择器)

此:

jQuery("#slideshow article", "#slideshow nav a").removeClass("current").removeAttr("class").eq(idx).addClass("current");

(这导致幻灯片停止工作,即使它没有引起错误,据我所知)

而且:

jQuery("#slideshow article").add("#slideshow nav a").removeClass("current").removeAttr("class").eq(idx).addClass("current");

仍然无效。我试过谷歌这个问题,并在没有运气的情况下阅读StackOverflow上的类似问题。有人可以帮忙吗?

编辑: Fiddle在合并之前一直正常工作(<nav>上的.current会变蓝)

1 个答案:

答案 0 :(得分:2)

原因:

问题是每个选择器都会创建一个jQuery集合,然后使用eq()为该集合中的特定元素编制索引。如果组合多个选择器,则只构建一个列表,因此eq()将始终只返回一个元素。

你真正想要的是一个关注组内元素索引的选择器。

答案:

由于每组选择恰好位于单个父级下,您可以使用 :nth-child() 过滤器执行此操作:

jQuery("#slideshow article, #slideshow nav a").removeAttr("class").filter(':nth-child(' + (idx+1) + ')').addClass("current");

最重要的是要记住,与其他索引选择器不同,nth-child是基于1的,而不是基于0的。这是为了匹配CSS nth-child等价物

JSFiddle:http://jsfiddle.net/33ueJ/4/

*注意:因为您要完全删除class属性,所以不需要先删除该类

<强>附录:

正如King King所指出的,在评论中,如果另一个HTML结构不支持使用 nth-child() ,您可以随时使用 nth-of-type() (只要两组元素是不同的元素类型。