JavaScript動態建立table表格

admin發表於2018-03-12

分享一段程式碼例項,能夠動態的建立一個表格並且填充表格資料。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
caption{
  padding:0 0 5px 0;
  width:450px;
  font:italic 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
  text-align:right;
}
td{
  border:1px solid #c1dad7;
  padding:6px 6px 6px 12px;
  color:#4f6b72;
  text-align:center;
  width:150px;
}
</style>
<script type="text/javascript"> 
var data=[{name:'螞蟻部落一',age:3,gender:'市南區'},{name:'螞蟻部落二',age:3,gender:'市南區'},{name:'螞蟻部落三',age:3,gender:'市南區'},{name:'螞蟻部落四',age:3,gender:'市南區'}]; 
 
onload = function(){ 
  var body=document.getElementsByTagName('body')[0]; 
  body.appendChild(createTable(data)); 
}; 
 
var createTable = function(data){ 
  var table=document.createElement('table'); 
  table.setAttribute('style','width: 450px;'); 
 
  var caption=document.createElement('caption'); 
  caption.innerHTML ='網站介紹'; 
 
  table.appendChild(caption);  
  table.appendChild(createTr('名稱','年齡','地址')); 
  table.childNodes[1].setAttribute('style','background:#cae8ea;');
    
  for(var i=0;i<data.length;i++){ 
    table.appendChild(createTr(data[i].name,data[i].age,data[i].gender)); 
  } 
  return table; 
}; 
 
 
var createTr = function(name,age,gender){ 
  var tr=document.createElement('tr'); 
  var tdName=document.createElement('td'); 
  tdName.innerHTML = name; 
  var tdAge = document.createElement('td'); 
 
  tdAge.innerHTML = age; 
  var tdGender = document.createElement('td'); 
  tdGender.appendChild(document.createTextNode(gender));
  tr.appendChild(tdName); 
  tr.appendChild(tdAge); 
  tr.appendChild(tdGender); 
 
  return tr; 
}; 
</script>
</head>
<body>
</body>
</html>

相關文章