首頁  >  文章  >  web前端  >  純原生js實作table表格的增刪

純原生js實作table表格的增刪

高洛峰
高洛峰原創
2017-01-07 10:12:371232瀏覽

公司實習生問我table的增刪操作,用jQuery很簡單的實作了。又問我不使用jQuery,只使用js如何實作。

面對這種情況,我的一貫做法是『不理解,但是支持』。

jQuery用的多了,人也懶了,但還是用js實現了這一操作,覺得困難在於IE相容。 。 。

只是想找程式碼看看的可以跳過分析過程,文章底部附有完整程式碼。

以下是coding流程:

HTML結構程式碼

一個基本的table結構,增加了一些簡單的樣式,三個按鈕分別對應建立、清空,和一個預留。

<!DOCTYPE HTML> 
<html> 
 <head> 
  <title>table</title> 
  <meta charset=&#39;utf-8&#39; /> 
  <style type="text/css"> 
   table.base{ 
    border-collapse:collapse; 
    text-align: center; 
    border: 1px solid black; 
   }  
   table, tr, td, th{ 
    border: 1px solid black; 
   }    
  </style> 
 </head> 
 <body> 
  <div id="main-content"> 
   <table id="main-table" class="base"> 
    <thead> 
     <tr> 
      <th colspan="3">This is a table for operations by javascript</th> 
     </tr> 
     <tr> 
      <th> 
       <input type="button" value="CREATE" id="cp_btn" onclick="createTr()" /> 
      </th> 
      <th> 
       <input type="button" value="CLEAR" id="cl_btn" onclick="clearTrs()" /> 
      </th> 
      <th> 
       <input type="button" value="GUESS" id="cl_btn"/> 
      </th> 
     </tr> 
    </thead> 
    <tbody> 
    </tbody> 
   </table> 
  </div> 
 </body> 
</html>

建構子(偽建構子)

考慮過,建立一個隱藏的tr,基於此tr執行建立操作。為了不破壞HTML整體結構,決定透過js產生tr物件並append到頁面中。

為了在頁面載入完成後,再執行dom操作,所以將<script>放在程式碼下端</script>

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn