WEB开发网
开发学院网页设计JavaScript JQuery和JS实现奇偶行不同背景颜色 阅读

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

 2012-11-17 17:24:28 来源:WEB开发网   
核心提示: JQuery实现:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="ht

 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></span><strong style="color: rgb(255, 0, 0); ">
</strong>

Tags:JQuery JS 实现

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接