首页 > 代码库 > javascript 对表格元素的快捷操作

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-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>New Web Project</title>
		<style>
			table{
				
				width: 500px;
			}
			td{
				border:1px solid #ccc;
				padding:5px;
			}
		</style>
		<script>
			window.onload=function(){
				var oTb=document.getElementById('tb');
				var oldColor=null;
				for(var i=0;i<oTb.tBodies[0].rows.length;i++)
				{
					oTb.tBodies[0].rows[i].onmouseover=function(){
						oldColor=this.style.background;
						this.style.background='red';
					};
					oTb.tBodies[0].rows[i].onmouseout=function(){
						this.style.background=oldColor;
					};
					if(i%2)
					{
						oTb.tBodies[0].rows[i].style.background='';
					}
					else
					{
						oTb.tBodies[0].rows[i].style.background='#ccc';
					}
				}
				
				
			};
		</script>
	</head>
	<body>
		<table id="tb">
			<thead>
				<tr>
					<td>ID</td>
					<td>姓名</td>
					<td>年龄</td>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>1</td>
					<td>张三</td>
					<td>23</td>
				</tr>
				<tr>
					<td>2</td>
					<td>李四</td>
					<td>26</td>
				</tr>
				<tr>
					<td>3</td>
					<td>王五</td>
					<td>29</td>
				</tr>
				<tr>
					<td>4</td>
					<td>青天决</td>
					<td>28</td>
				</tr>
				<tr>
					<td>5</td>
					<td>赵少邦</td>
					<td>23</td>
				</tr>
			</tbody>
		</table>
	</body>
</html>

运行结果图:


通过上述代码可以看出 javascript 里内置了对于表格元素的快捷操作 

1. oTb.tBodies[0].rows[i] 获取tBody的某一行

2. oTb.tBodies[0].rows[i].cells[i] 获取tbody里的某一行 某一列


javascript 对表格元素的快捷操作