2012-05-21 117 views
3

我如何編寫使用for(i = 1; ...)的短代碼?函數,允許我遍歷每個孩子並添加一個不同的類。每個孩子的循環jQuery

$('#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'); 

回答

9

嘗試

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

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

如果'#WebPartWPQ3'具有不表子節點?可能會更好地遍歷$('#WebPartWPQ3')。children()'並檢查它們是否是表。 – DCoder