循环遍历jQuery子元素的方法

3

我要写一个短代码,使用for(i=1; ... ...)函数循环通过每个子元素并添加不同的类,该怎么做?

$('#WebPartWPQ3 > table:first-child').addClass('blogpost1');
$('#WebPartWPQ3 > table:nth-child(2)').addClass('blogpost2');
$('#WebPartWPQ3 > table:nth-child(3)').addClass('blogpost3');
$('#WebPartWPQ3 > table:nth-child(4)').addClass('blogpost4');
$('#WebPartWPQ3 > table:nth-child(5)').addClass('blogpost5');
$('#WebPartWPQ3 > table:nth-child(6)').addClass('blogpost6');
$('#WebPartWPQ3 > table:nth-child(7)').addClass('blogpost7');
$('#WebPartWPQ3 > table:nth-child(8)').addClass('blogpost8');
$('#WebPartWPQ3 > table:nth-child(9)').addClass('blogpost9');
1个回答

9

试一试

$('#WebPartWPQ3 > table').each(function(i,j){

 $(this).addClass("blogpost"+(i+1));
});

4
如果 #WebPartWPQ3 元素拥有不是表格的子节点,那么循环遍历 $('#WebPartWPQ3').children() 并检查它们是否为表格可能会更好。 - DCoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接