我正在尝试以每 6 个中的第 3 个 .foo
元素为目标。下面是我的意思的一个小例子:
1
2
3 (this)
4
5
6
1
2
3 (this)
4
5
6
and so on...
据我所知,它只针对每个第 3 个元素,但这不太正确,因为它也针对第一个 .foo
:http://jsfiddle.net/neal_fletcher/Bb4Hv/
$('.foo').each(function() {
if(!($('.foo').index(this) % 3)) {
$( this ).css( "background-color", "red" );
}
});
对于如何实现我所说明的内容的任何建议,我们将不胜感激!
最佳答案
我个人更喜欢 nth-child()
方法(正如@Arbel 所建议的那样),但要使其正常工作,请对您的问题代码进行微小更改:
$('.foo').each(function() {
if(!(($('.foo').index(this)-2) % 6)) {
$( this ).css( "background-color", "red" );
}
});
毕竟,您实际上想要每第 6 个元素,只是从偏移 2 开始
作为次要注意事项,jQuery 函数实际上将索引和元素( native 元素)传递给迭代器函数,因此您可以将上面的内容更改为
$('.foo').each(function(i,ele) {
if(!((i-2) % 6)) {
$(ele).css( "background-color", "red" );
}
});
编辑
我提到我更喜欢 nth-child
方法,但从一些评论来看,也许 nth-of-type
可能更适合您的要求。
链接仅供引用:
和
CSS Tricks comparison of the two
nth-of-type
示例
.foo:nth-of-type(6n-3)
{
background-color: red;
}
注意:建立所需元素的公式不同的原因(即 i-2 % 6 或 6n-3)是 javascript 以索引 0 开头第一个元素,CSS 以 1 开头(对于 nth-child 或 nth-of-type 选择器中的 n)
关于javascript - jQuery:定位每 6 个中的第 3 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376083/