jquery第n个子选择器问题

发布于 2024-11-02 03:22:33 字数 128 浏览 1 评论 0原文

我想在 div 中选择图像。我想要的图像编号为 2、5、8、11 等。

$('.thediv img:nth-child(3n+1)').. 

不适合我,我错过了什么吗?谢谢

I want to select images in a div. The images i want are number 2,5,8,11 etc.

$('.thediv img:nth-child(3n+1)').. 

Did not work for me, did i miss something? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

童话 2024-11-09 03:22:33

您的公式 3n + 1 不起作用,因为这些是将为以下 n 值选择的元素:

3(0) + 1 = 0 + 1 = 1
3(1) + 1 = 3 + 1 = 4
3(2) + 1 = 6 + 1 = 7
3(3) + 1 = 9 + 1 = 10
...

显然,这些不是第二个、第五个、第 8 个、第 11 个...选定的元素。它们中的每一个都相差 1。您需要使用公式 3n + 2 来代替,因此将选择这些元素:

3(0) + 2 = 0 + 2 = 2
3(1) + 2 = 3 + 2 = 5
3(2) + 2 = 6 + 2 = 8
3(3) + 2 = 9 + 2 = 11
...

并且因为您在评论中说每个 img位于 a 中,:nth-child() 伪类应附加到 a,然后选择 img :

$('.thediv a:nth-child(3n+2) img')

Your formula 3n + 1 doesn't work because these are the elements that will be selected for the following values of n:

3(0) + 1 = 0 + 1 = 1
3(1) + 1 = 3 + 1 = 4
3(2) + 1 = 6 + 1 = 7
3(3) + 1 = 9 + 1 = 10
...

Clearly, these aren't the 2nd, 5th, 8th, 11th ... elements selected. Each of them is off by 1. You need to use the formula 3n + 2 instead, so these elements will be selected:

3(0) + 2 = 0 + 2 = 2
3(1) + 2 = 3 + 2 = 5
3(2) + 2 = 6 + 2 = 8
3(3) + 2 = 9 + 2 = 11
...

And since you said in your comment that each img is in an a, the :nth-child() pseudo-class should be attached to a, then you select the img:

$('.thediv a:nth-child(3n+2) img')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文