首页 > 代码库 > js操作table

js操作table

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head>  <title> New Document </title>  <style type="text/css">        table        {            border-collapse: collapse;            border: none;            width: 200px;        }        td        {            border: solid #000 1px;        }    </style>    <script>      //获得当前域在的index ,(是第几个xxx)      function getElementOrder(field,tableid){        var inputs = document.getElementsByName(field.name);        var len = inputs.length;        var index = 0;        for  (var i = 0 ; i < len; i++){              if(inputs == field ){                  index = i;                  break;                            }                }        return index;      }     function insertRow(tableid,table_data){   //获得tbody (创建一个table会有一个默认的 tbody 装载 tr td 这里获得tale一个tbody)     var oTBODY     = document.getElementById(tableid).tBodies[0];//此处相当于item(0)在js中使用数组序号直接调用即可 见javascript权威指南P368     var oTBODYData = document.getElementById(table_data).tBodies[0];          var  len = oTBODYData.rows.length;     //遍历data 行     for ( var i = 0 ; i <= len; i++ ){       oTBODY.appendChild(oTBODYData.rows[i].cloneNode(true));     }         }    function deleteRow(Field,targetTable){       var findex = getElementOrder(Field)-1;//此处减1是因sourceTable中有一行是隐藏的        document.getElementById(targetTable).deleteRow(findex);    }    </script> </head> <body>      <table id = "table_data" class="data"  style ="display:none">          <tr>            <td><input type="text" name="">1</td>            <td><input type="text" name="2"></td>             <td><input type="text"></td>              <td><input type="button" value="删除" onclick="deleteRow(this,‘table_list‘);"></td>          </tr>                </table>           <table id = "table_list" class ="list">      <tr>        <td>年龄 <td>        <td>性别</td>        <td><input type="button"  name ="del"  onclick="deleteRow(this)"></td>        <td><input type="button"  value ="添加" name ="insert"  onclick="insertRow(‘table_list‘,‘table_data‘)"></td>      </tr>      </table> </body></html>

 

方法很常见了,不敲一遍谁赶说自己会呢。

 

js操作table