欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中動(dòng)態(tài)向表格添加數(shù)據(jù)

 更新時(shí)間:2017年01月24日 09:50:31   作者:ChauncyWu  
本文給大家分享使用原生javascript實(shí)現(xiàn)動(dòng)態(tài)向表格中添加數(shù)據(jù)的方法,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧

利用JavaScript ,動(dòng)態(tài)向表格中添加數(shù)據(jù),其實(shí)方法很簡(jiǎn)單的,下面給大家分享下實(shí)現(xiàn)方法

1. 首先先寫出表格的表頭和主干部分

<table width="600" border="1" cellspacing="0"> 
  <thead> 
   <tr> 
     <th>編號(hào)</th> 
     <th>姓名</th> 
     <th>職位</th> 
     <th>操作</th> 
   </tr>  
  </thead> 
  <tbody id="tbMain"></tbody> 
</table> 

2. 接下來就是網(wǎng)表格里面添加數(shù)據(jù),這里用的是原生javascript

<script type="text/javascript"> 
 //模擬一段JSON數(shù)據(jù),實(shí)際要從數(shù)據(jù)庫(kù)中讀取 
 var per = [ 
      {id:001,name:'張珊',job:'學(xué)生'}, 
      {id:002,name:'李斯',job:'教師'}, 
      {id:003,name:'王武',job:'經(jīng)理'} 
      ];  
 window.onload = function(){ 
   var tbody = document.getElementById('tbMain'); 
   for(var i = 0;i < per.length; i++){ //遍歷一下json數(shù)據(jù) 
     var trow = getDataRow(per[i]); //定義一個(gè)方法,返回tr數(shù)據(jù) 
     tbody.appendChild(trow); 
    } 
   } 
 function getDataRow(h){ 
   var row = document.createElement('tr'); //創(chuàng)建行 
   var idCell = document.createElement('td'); //創(chuàng)建第一列id 
   idCell.innerHTML = h.id; //填充數(shù)據(jù) 
   row.appendChild(idCell); //加入行 ,下面類似 
   var nameCell = document.createElement('td');//創(chuàng)建第二列name 
   nameCell.innerHTML = h.name; 
   row.appendChild(nameCell); 
   var jobCell = document.createElement('td');//創(chuàng)建第三列job 
   jobCell.innerHTML = h.job; 
   row.appendChild(jobCell); 
   //到這里,json中的數(shù)據(jù)已經(jīng)添加到表格中,下面為每行末尾添加刪除按鈕 
   var delCell = document.createElement('td');//創(chuàng)建第四列,操作列 
   row.appendChild(delCell); 
   var btnDel = document.createElement('input'); //創(chuàng)建一個(gè)input控件 
   btnDel.setAttribute('type','button'); //type="button" 
   btnDel.setAttribute('value','刪除');  
   //刪除操作 
   btnDel.onclick=function(){ 
     if(confirm("確定刪除這一行嘛?")){ 
       //找到按鈕所在行的節(jié)點(diǎn),然后刪掉這一行 
       this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); 
       //btnDel - td - tr - tbody - 刪除(tr) 
       //刷新網(wǎng)頁(yè)還原。實(shí)際操作中,還要?jiǎng)h除數(shù)據(jù)庫(kù)中數(shù)據(jù),實(shí)現(xiàn)真正刪除 
       } 
     } 
   delCell.appendChild(btnDel); //把刪除按鈕加入td,別忘了 
   return row; //返回tr數(shù)據(jù)   
   }   
</script> 

3. 網(wǎng)頁(yè)測(cè)試

顯示成功,點(diǎn)擊刪除按鈕,并確定即可刪除這一行

刪除第二行,可以!

以上所述是小編給大家介紹的JavaScript中動(dòng)態(tài)向表格添加數(shù)據(jù),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論