每2行添加一个CSS类
我有一张这样的桌子:
Test Test Test Test Test Test Test Test Test Test Test Test Test Test
我想在每两行后添加一个CSS类alt
,所以例如我将有一个2个白色行,2个红色行,2个白色行,2个红色行等的序列。 这可以用JQuery吗?
http://jsbin.com/okahax/edit#javascript,html
var t = 0; $("table tr").each(function (i, n) { if (t < 2) {$(this).css('background-color','red'); } else if (t < 4) { $(this).css('background-color','white'); } t++; if (t==4) t=0; })
像这样的东西:
$('tr:nth-child(4n),tr:nth-child(4n-1)').addClass('alt');
这使用具有适当等式的第n个子选择器 。
演示: http : //jsfiddle.net/cnQNx/
要么:
$('tr:nth-child(4n)').prev().andSelf().addClass('alt');