注:本笔记内容摘自《jQuery基础教程》+ jQuery 1.4.1中文参考
三色交替模式
如果我们需要为表格应用更复杂的条纹效果,例如三色交替的模式。为实现这种模式,首先需要为三行定义CSS规则。同时添加相应的类名:
tr.even,
tr.first{
background-color:#eee;
}
tr.odd,
tr.second{
background-color:#ddd;
}
tr.third{
background-color:#ccc;
}
现在来观察一下每一行除以3的余数有什么规律:
0%3 = 0 1%3= 1 2%3 = 2
3%3 = 0 4%3= 1 5%3 = 2
6%3 = 0 7%3= 1 8%3 = 2
以此类推,我们的余数在0-2范围内,所以要使用3作为除数,将行号作为被除数。利用each()方法内置的index作为被除数。
$(document).ready(function(){
varclassNames = {
0:’first’,
1:’second’,
2,’third’
};
$(‘table.striped tbody tr’).not(‘[th]’).each(function(index){
$(this).addClass(classNames[index%3]);
});
});
这样就可以看到页面的三色交替的效果了。
同理我们也可以进行更多颜色的交替设置了。