JavaScript遍历table

JavaScript遍历table


1、说明

     遍历表格中的某行某列,并打印其值


2、实现源代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript遍历table</title>
<style type="text/css">
    tr td,tr th{
		border:#CCC 1px solid;
	}
</style>
<script type="text/javascript">
     /**
	  * JavaScript遍历table
	  */
     function eachTableRow()
	 {
		 //获取table序号
		 var tab=document.getElementById("tab");
		 //获取行数
     	 var rows=tab.rows;
		 //遍历行
     	 for(var i=1;i<rows.length;i++)
     	{
			//遍历表格列
        	for(var j=0;j<rows[i].cells.length;j++)
        	{
				//打印某行某列的值
       			alert("第"+(i+1)+"行,第"+(j+1)+"列的值是:"+rows[i].cells[j].innerHTML);
        	}
     	}
	 }
</script>
</head>

<body>
   <table id="tab" cellpadding="0" cellspacing="0" style="width:50%; text-align:center; border:#CCC 1px solid;">
       <tr style="border:#CCC 1px solid;">
         <th>学号</th>
         <th>姓名</th>
         <th>年龄</th>
         <th>性别</th>
       </tr>
       <tr>
         <td>2014010101</td>
         <td>张思思</td>
         <td>20</td>
         <td>女</td>
       </tr>
       <tr>
         <td>2014010102</td>
         <td>立三</td>
         <td>21</td>
         <td>男</td>
       </tr>
       <tr>
         <td>2014010103</td>
         <td>王玉</td>
         <td>22</td>
         <td>女</td>
       </tr>
       <tr>
         <td>2014010104</td>
         <td>朱莉</td>
         <td>23</td>
         <td>男</td>
       </tr>
   </table>
   <input type="button" value="遍历" onclick="eachTableRow()"/>
</body>
</html>


3、实现结果

(1)初始化时



(2)单击“遍历”



(3)再次单击“遍历”


posted @ 2017-05-25 12:48  claireyuancy  阅读(1703)  评论(0编辑  收藏  举报