为每个孩子循环jQuery

max*_* li 3 javascript jquery loops

我如何编写使用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');
Run Code Online (Sandbox Code Playgroud)

Raf*_*fay 9

尝试

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

 $(this).addClass("blogpost"+(i+1));
});
Run Code Online (Sandbox Code Playgroud)

  • 如果`#WebPartWPQ3`有子节点不是表怎么办?可能更好地循环`$('#WebPartWPQ3').children()`并检查它们是否是一个表. (4认同)