当前可见的jquery第n个孩子 [英] jquery nth child that is currently visible

查看:39
本文介绍了当前可见的jquery第n个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以像这样设置每 4 个项目"div 的样式

I can style every 4th 'item' div like so

  jQuery(".item:nth-child(4n)").addClass("fourth-item");

效果很好,但是我隐藏了一些项目,显示了一些其他项目并想要重新进行此样式设置,但仅对每个可见的第 4 个项目进行样式设置.所以我有一个函数可以删除这个样式并重新应用它,但我需要在重新应用样式时指定它只是每 4 个可见项目,而不是每 4 个项目.我知道 ":visible" 选择器,但看不到将它与 nth-child 选择器正确链接,有什么想法吗?

and that works fine, but then I hide some items, show some others and want to re-do this styling, but only styling every 4th item that is visible. So I have a function that will remove this styling and reapply it, but I need to specify in the reapplying of the style that it is only every 4th visible item, not every 4th item. I know the ":visible" selector but can't seen to chain it with the nth-child selector properly, any ideas?

我尝试过各种类似的方法都无济于事......

I've tried various things like this to no avail...

jQuery(".item").removeClass("fourth-item");
jQuery(".item:visible:nth-child(4n)").addClass("fourth-item");

推荐答案

:nth-child 扫描父母的孩子,无论他们的样式是什么.:nth-child 中的计数是相对于父元素,而不是前一个选择器.这在 :nth-child:

使用:nth-child(n),所有子元素都被计算在内,无论它们是什么,并且只有当指定的元素与附加到伪类的选择器匹配时才会被选中.

With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class.

each 使用更简单的方法完全符合您的要求:

Using a more simple method with each does exactly what you want:

$('#test li:visible').each(function (i) {
    if (i % 4 == 0) $(this).addClass('fourth-item');
});

这篇关于当前可见的jquery第n个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆