!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload = function() {
var tblEle = document.getElementsByClassName("listtable");
//2、获取表格中tbody里面的行数
//采用角标tblEle[0]确定获取的对像。索引从0开始
var len = tblEle[1].tBodies[0].rows.length;
//3、对tbody里面的行进行遍历
for (var i = 0; i < len; i++) {
if (i % 2 == 0) {
tblEle[1].tBodies[0].rows[i].style.backgroundColor = "yellow";
} else {
tblEle[1].tBodies[0].rows[i].style.backgroundColor = "green";
}
}
}
</script>
</head>
<body>
<table border="1" width="500" height="50" align="center" class="listtable">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>张三</td>
<td>22</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>25</td>
</tr>
</tbody>
</table>
<br />
<br />
<table border="1" width="500" height="50" align="center" class="listtable">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>张三</td>
<td>22</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>25</td>
</tr>
</tbody>
</table>
</body>
</html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload = function() {
//1、获取表格
//不仅能获得表格对象,可以获得各种类型的对象,例如<span>标签、<p>标签、<div>等
var tblEle = document.getElementsByClassName("listtable");
//2、获取表格中tbody里面的行数
//采用角标tblEle[0]确定获取的对像。索引从0开始
var len = tblEle[1].tBodies[0].rows.length;
//3、对tbody里面的行进行遍历
for (var i = 0; i < len; i++) {
if (i % 2 == 0) {
tblEle[1].tBodies[0].rows[i].style.backgroundColor = "yellow";
} else {
tblEle[1].tBodies[0].rows[i].style.backgroundColor = "green";
}
}
}
</script>
</head>
<body>
<table border="1" width="500" height="50" align="center" class="listtable">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>张三</td>
<td>22</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>25</td>
</tr>
</tbody>
</table>
<br />
<br />
<table border="1" width="500" height="50" align="center" class="listtable">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>张三</td>
<td>22</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>25</td>
</tr>
</tbody>
</table>
</body>
</html>