動態刪除表格行及表格行的上移下移操作

動態添加刪除表格的行:

  1. //動態添加一行  
  2. function addRow() {  
  3.     var table = $("#sample");  
  4.     var tr = $("#sample tr").eq(0).clone(true);  
  5.     tr.find("input:eq(0)").val("");  
  6.     tr.find("input:eq(1)").val("");  
  7.     tr.appendTo(table);  
  8. }  
  9.  
  10. //動態刪除一行  
  11. function deleteRow(obj) {  
  12.     var rowCount = $("#sample tr").size();  
  13.     if(rowCount == 1) {             
  14. alert("至少保留一行");                
  15. return;  
  16.     }  
  17.     $(obj).parent().parent().remove();  
  18. }  
  19.  
  20. <table id="sample"> 
  21.     <tr> 
  22.         <td><input type="text" name="input1"></td>                              <td><input type="text" name="input2"></td> 
  23.         <td><a href="#" onclick="return deleteRow(this);">刪除</a></td> 
  24.     </tr> 
  25. </table> 

表格行的上移、下移

  1. //上移  
  2. function moveUp(obj) {  
  3.     var rowCount = $("#sample tr").size();  
  4.     var curRow = $(obj).parent().parent().prevAll().length + 1; //獲取當前行是第幾行  
  5.     if (curRow == 1){  
  6.          alert("第一行不可以上移");  
  7.     } else {  
  8.          var curTr = $(obj).parent().parent();  
  9.          var preTr = curTr.prev();  //獲取當前行的上一行  
  10.          var preTrpreTrClone = preTr.clone(true);  
  11.          curTr.after(preTrClone);  //在curTr後插入一行  
  12.          preTr.remove();  
  13.     }  
  14. }  
  15.  
  16. //下移  
  17. function moveDown(obj) {  
  18.     var rowCount = $("#sample tr").size();  
  19.     var curRow = $(obj).parent().parent().prevAll().length + 1;  
  20.     var count = rowCount - curRow;  
  21.     if (count == 0) {  
  22.          alert("當前行不可以下移");  
  23.     } else {  
  24.          var curTr = $(obj).parent().parent();  
  25.          var nextTr = curTr.next(); //獲取當前行的下一行  
  26.          var curTrcurTrClone = curTr.clone(true);  
  27.          nextTr.after(curTrClone);  
  28.          curTr.remove();  
  29.     }  
  30. }  
  31.  
  32. <table id="sample"> 
  33.     <tr> 
  34.         <td>aaa</td> 
  35.         <td>bbb</td> 
  36.         <td><a href='#' onclick='moveUp(this)'>上移</a>&nbsp;|&nbsp;<a href='#' onclick='moveDown(this)'>下移</a></td> 
  37.     </tr> 
  38.      <tr> 
  39.         <td>ccc</td> 
  40.         <td>ddd</td> 
  41.         <td><a href='#' onclick='moveUp(this)'>上移</a>&nbsp;|&nbsp;<a href='#' onclick='moveDown(this)'>下移</a></td> 
  42.     </tr> 
  43.     <tr> 
  44.         <td>eee</td> 
  45.         <td>fff</td> 
  46.         <td><a href='#' onclick='moveUp(this)'>上移</a>&nbsp;|&nbsp;<a href='#' onclick='moveDown(this)'>下移</a></td> 
  47.     </tr> 
  48. </table> 

 

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