JavaScript獲取table表格行與列的數量

admin發表於2018-06-29

本章節介紹一下如何利用JavaScript獲取一個表格的行和列的數目。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>table細線表格-螞蟻部落</title> 
<style type="text/css">  
#thetable{ 
  background-color:green; 
  font-size:12px; 
} 
#thetable th{ 
  text-align:center; 
  background-color:#CCF; 
  height:30px; 
  line-height:30px; 
} 
#thetable td{ 
  width:150px; 
  height:30px; 
  line-height:30px; 
  text-align:center; 
  background-color:#FFF; 
} 
</style> 
<script type="text/javascript">
window.onload=function(){
  var otable=document.getElementById("thetable");
  var oshow=document.getElementById("show");
  oshow.innerHTML="行的數目:"+otable.rows.length+"<br/>"
  +"列的數目:"+otable.rows[0].cells.length;
}
</script> 
</head>  
<body>  
<div id="show"></div>
<table cellpadding="0" cellspacing="1" id="thetable"> 
  <tr> 
    <th>標題一</th> 
    <th>標題二</th> 
    <th>標題三</th> 
    <th>標題四</th> 
  </tr> 
  <tr> 
    <td>螞蟻部落一</td> 
    <td>螞蟻部落二</td> 
    <td>螞蟻部落三</td> 
    <td>螞蟻部落四</td> 
  </tr> 
  <tr> 
    <td>螞蟻部落一</td> 
    <td>螞蟻部落二</td> 
    <td>螞蟻部落三</td> 
    <td>螞蟻部落四</td> 
  </tr> 
  <tr> 
    <td>螞蟻部落一</td> 
    <td>螞蟻部落二</td> 
    <td>螞蟻部落三</td> 
    <td>螞蟻部落四</td> 
  </tr> 
</table> 
</body>  
</html>

相關文章