js table

<!--本段代碼粘貼到記事本,轉成html即可使用-->

<html>
<head>
   <title>js添加刪除行</title>

   <script type="text/javascript">
  

//要確定行的唯一性(提示:你可以使用你的主鍵)
   var id=1;
//添加行的方法
   function addTr()
   { 
    //獲得表格對象
    var tb=document.getElementById('testTab');
   
    //添加一行    
    var newTr = tb.insertRow(-1);//在最下的位置
   
    //給這個行設置id屬性,以便於管理(刪除)
    newTr.id='tr'+id;
    //設置對齊方式(只是告訴你,可以以這種方式來設置任何它有的屬性)
    newTr.align='center';
    //添加兩列    
    var newTd0 = newTr.insertCell();    
    var newTd1 = newTr.insertCell();
   
    //設置列內容和屬性    
    newTd0.innerHTML = "本行id爲:"+id; //讓你看到刪除的是指定的行
    newTd1.innerHTML= "<button onclick=/"moveTr('"+id+"');/" >移除</button>";;
   
    id++;
   
   }
   //移除行的方法
   function moveTr(id)
   {
    //獲得表格對象
    var tb=document.getElementById('testTab');
    //根據id獲得將要刪除行的對象
    var tr=document.getElementById('tr'+id);
    //取出行的索引,設置刪除行的索引
    tb.deleteRow(tr.rowIndex);
   
     //清空列表,移除全部行的方法
     //while(tb_show.hasChildNodes()){
     //tb_show.deleteRow();
     //}

   }

   </script>
</head>
<body>
   <center>

   表格:
   <table id="testTab" border="1" bordercolor="red" width="700px" height="300px">
    <tr>
     <td>
      操控此表格
     </td>
     <td>
      第二列
     </td>
    </tr>
   </table>
   <button onclick="addTr();">添加一行</button>
   </center>
</body>
</html>

<!--

不知道看了這段代碼後你又掌握了多少?代碼是死的,要靈活運用,刪除指定行,在任意位置添加行、任意位置添加列、修改任意表格內的內容,其實方法都是類似的,關鍵看大家的運用方式!

歡迎加入java羣:63353323
本人qq:287572694

slzs....

補充其它刪行方法:table.removeChild(this.parentNode.parentNode); 根據節點而定

--removeChild(tr.children[index]);

-->

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章