首页 > 程序开发 > web前端 > JavaScript >

JQuery和JS实现奇偶行不同背景颜色

2012-11-19

JQuery实现:[javascript]<!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-...

JQuery实现:

[javascript]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html xmlns="https://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(){
//可以是:$(&#39;#t1 tbody tr:even&#39;).css(&#39;background&#39;,&#39;red&#39;);
$(&#39;#t1 > tbody tr:even&#39;).css(&#39;background&#39;,&#39;red&#39;);
$(&#39;#t1 > tbody tr:odd&#39;).css(&#39;background&#39;,&#39;blue&#39;);
});
</script>
</head>


<body>
<table id="t1" width="500px" align="center">
<tbody> www.2cto.com
<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实现:

[javascript]
<span style="color:#333333;"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html xmlns="https://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></span><strong style="color: rgb(255, 0, 0); ">
</strong>

相关文章
最新文章
热点推荐