動態增加刪除行 js

所做過的多個項目中均用到js動態添加刪除行的應用,在寫過多種方案後,最終整理出這個最爲方便應用的方案,以備日後拿來便用:

以下是DEMO全部代碼:


<html>
 <head>
  <title>Ace Test</title>
<script language="JavaScript">   
  var cGetRow=-99999;
  function insertrow(){
  var newrow = document.all.ACE_HIDDEN_TABLE.rows[0].cloneNode(true); //克隆一行
  document.all("newTB").appendChild(newrow); //添加剛纔克隆的一行
  }
    

  function GetRow(){
 //獲得行索引
 //兩個parentElement分別是TD和TR,rowIndex是TR的屬性
 //this.parentElement.parentElement.rowIndex
    cGetRow=window.event.srcElement.parentElement.parentElement.rowIndex;
   
    DelRow(cGetRow);//點擊checkbox時,直接刪除行。
  }
  function DelRow(iIndex){
 //刪除一行
 if(iIndex==-99999){
   alert("系統提示:沒有選中行號!");
 }else{
   newTB.deleteRow(iIndex);
   iIndex==-99999;//將rowIndex恢復默認值。
 }
  }
  </script>
 </head>

 <body class="dialog_body">
  <form method="POST" onSubmit="return   doSubmit(this)">
 
    
     <table border="1" width="900" cellpadding="0" cellspacing="0" class="table">
     
      <!-- 隱藏table,用於克隆的行 begin -->
      <tbody id="ACE_HIDDEN_TABLE" style="display:none">
       <tr>
        <td><input type="checkbox" οnclick="GetRow()"/></td>
        <td width="16%">
         <select id="pid" name="project"">
          <option value=""></option>
          <option value="0">
           人員編號
          </option>
          <option value="1">
           姓名
          </option>
         </select>
        </td>
        <td width="16%">
         <input id="result" type="text" value="" readonly="true">
        </td>
       </tr>
      </tbody>
     </table>
     <!-- 隱藏table,用於克隆的行 end -->
     
     <table border="1" width="900" cellpadding="0" cellspacing="0" class="table">
      <!-- 插入新行的區域 begin -->
      <tbody id="newTB">
      </tbody>
      <!-- 插入新行的區域 end -->
     </table>

   <div align="right" style="margin:10px;">
    <input type="button" onClick="insertrow();" value="增加一行">
    <input type="button" onClick="DelRow(cGetRow);" value="刪除一行">
   </div>
   
  </form>
 </body>
</html>

 

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