gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:18:14 24 4
gpt4 key购买 nike

目前,我有这个 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");

还是不行。我尝试用 Google 搜索这个问题,并在 StackOverflow 上阅读类似的问题,但没有成功。有人可以帮忙吗?

编辑: Fiddle在合并之前工作正常(<nav> 上的.current 应该变成蓝色)

最佳答案

原因:

问题是每个选择器都会创建一个 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/

*注意:由于您要完全删除类属性,因此不需要先删除该类

附录:

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

关于javascript - 在 jQuery 中选择多个元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com