最近没事做,写了个js 动态加载table的tr隔行换色,用了rowIndex 这个属性,贴上我研究的代码,鉴于本人的水平有限,见笑了,如果您有好的实现方法,欢迎交流一下,谢谢!
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<
table
style
="BORDER-COLLAPSE:collapse"
cellSpacing
=0
width
=600
align
=center
border
=1
cellpadding
="0"
bordercolor
="#CCCCCC"
>
< tr >
< td width ="200px;" > a </ td >
< td width ="200px;" > sd </ td >
< td width ="200px;" > asdf </ td
</tr >
< tr >
< td width ="200px;" > b </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
< tr >
< td width ="200px;" > c </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
< tr >
< td width ="200px;" > c </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
< tr >
< td width ="200px;" > c </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
</ table >
< tr >
< td width ="200px;" > a </ td >
< td width ="200px;" > sd </ td >
< td width ="200px;" > asdf </ td
</tr >
< tr >
< td width ="200px;" > b </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
< tr >
< td width ="200px;" > c </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
< tr >
< td width ="200px;" > c </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
< tr >
< td width ="200px;" > c </ td >
< td width ="200px;" > a </ td >
< td width ="200px;" > a </ td
</tr >
</ table >
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1
function fun(){
2 var tr=document.getElementsByTagName("tr");
3 for(var i=0;i < tr .length;i++)
4 {
5 tr[i].style.background =tr[i].rowIndex % 2 ==0?"#F0FFF0":"white";
6 }
7 }
8
9 window.onload =fun;
2 var tr=document.getElementsByTagName("tr");
3 for(var i=0;i < tr .length;i++)
4 {
5 tr[i].style.background =tr[i].rowIndex % 2 ==0?"#F0FFF0":"white";
6 }
7 }
8
9 window.onload =fun;
最终效果截图
小结
rowIndex用于判断当前单元格所处行的索引(从0开始)
cellIndex用于判断当前单元格所处列的索引(从0开始)