JQuery實現:
復制代碼 代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<script type="text/javascript" src="jquery-core/jquery-1.8.0.js"></script>
<script type="text/javascript">
$(function(){
//可以是:$('#t1 tbody tr:even').css('background','red');
$('#t1 > tbody tr:even').css('background','red');
$('#t1 > tbody tr:odd').css('background','blue');
});
</script>
</head>
<body>
<table id="t1" width="500px" align="center">
<tbody>
<tr><td>aaaaaaa</td></tr>
<tr><td>bbbbbbb</td></tr>
<tr><td>ccccccc</td></tr>
<tr><td>ddddddd</td></tr>
<tr><td>eeeeeee</td></tr>
<tr><td>fffffff</td></tr>
<tr><td>ggggggg</td></tr>
<tr><td>hhhhhhh</td></tr>
</tbody>
</table>
</body>
</html>
JS實現:
復制代碼 代碼如下:
<span style="color:#333333;"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<script type="text/javascript">
//頁面加載事件
window.onload=function(){
//獲取table
var tb1 = document.getElementById("t1");
//獲取table中的tbody
var tbody = tb1.getElementsByTagName("tbody")[0];
//獲取tr
var trs = tbody.getElementsByTagName("tr");
//根據奇、偶行顯示不同的背景顏色
for(var i=0; i<trs.length;i++){
if(i%2==0){
trs[i].style.backgroundColor="red";
}else{
trs[i].style.backgroundColor="blue";
}
}
}
</script>
</head>
<body>
<table id="t1" width="500px" align="center">
<tbody>
<tr><td>aaaaaaa</td></tr>
<tr><td>bbbbbbb</td></tr>
<tr><td>ccccccc</td></tr>
<tr><td>ddddddd</td></tr>
<tr><td>eeeeeee</td></tr>
<tr><td>fffffff</td></tr>
<tr><td>ggggggg</td></tr>
<tr><td>hhhhhhh</td></tr>
</tbody>
</table>
</body>
</html>