使用jquery将类添加到具有特定类的父级的第n个子级

时间:2012-02-22 13:27:17

标签: jquery css-selectors

最好用小提琴解释:http://jsfiddle.net/hxsJx/

我想在元素的第n个子元素中添加一个类,但只有当这些子元素具有特定的类时。所以在我的例子中,只有文章E和J应该得到'结束'的类。

nth-child选择器似乎忽略了类选择器,这可能是预期的行为,但我找不到解决方法。

感谢任何人们......

3 个答案:

答案 0 :(得分:1)

选择器按预期工作。请记住,CSS :nth-child选择器是基于一个的(它从一开始计数)。

4n个元素是DH,确实有1个字段。

你的选择器:.articles article.1:nth-child(4n)

HTML:

<section class="articles">          .articles
<article class="1 4">A</article>        :nth-child(1)
<article class="1 4">B</article>        :nth-child(2)
<article class="2 2">C</article>        :nth-child(3)
<article class="1">D</article>          :nth-child(4)  and  :nth-child(4n) and .1
<article class="1">E</article>          :nth-child(5)
<article class="3 2">F</article>        :nth-child(6)
<article class="1 4">G</article>        :nth-child(7)
<article class="1 2">H</article>        :nth-child(8)  and  :nth-child(4n) and .1
<article class="1 3 4">I</article>      :nth-child(9)
<article class="1 2 4">J</article>      :nth-child(10)
</section>

答案 1 :(得分:0)

尝试Lettering.js http://letteringjs.com/

答案 2 :(得分:0)

不,Rob W是对的。

//$('.articles article').removeClass('end');
$('.articles article.1:nth-child(4n)').addClass('end');​

使D和H成为目标,但如果将其设置为

//$('.articles article').removeClass('end');
$('.articles article.1:nth-child(5n)').addClass('end');​

E和J成为目标。

编辑:第4个孩子是D和H.D等于4,H等于8.

1 = A
2 = B
3 = C
4 = D
等等,你的数字混乱了。 E和J分别是第5和第10个孩子。

相关问题