现在的位置: 首页 > 综合 > 正文

js控制html中table行的增加和删除 (转)

2018年04月15日 ⁄ 综合 ⁄ 共 1820字 ⁄ 字号 评论关闭

<html>
 <head>
  <title>Adding and Removing Rows from a table using DHTML and JavaScript</title>
  <script language="javascript">
    function addRow()
   {
     var newRow = document.all("tblGrid").insertRow();

  //得到表的对象并插入一行,下面是插入了行以后,填充相应的列节点,如下面所示
     var oCell = newRow.insertCell();//插入列的节点
     oCell.innerHTML = "<input type='text' name='t1'>";//列里面填充的值,innerHtml值列内的所有元素   
    oCell = newRow.insertCell();
    oCell.innerHTML = "<input type='text' name='t2'>";
  
    oCell = newRow.insertCell();
    oCell.innerHTML = "<input type='text' name='t3'> &nbsp;&nbsp;<input type='button' value='Delete' onclick='removeRow(this);'/>"; 
   }
   function removeRow(src)
   {
    var oRow = src.parentElement.parentElement;  //获取当前事件的父节点
    document.all("tblGrid").deleteRow(oRow.rowIndex);  //删除当前列
   }
 
  </script>
 </head>
 <body>
    <table id="tblGrid" style="table-layout:fixed">
   <tr>
    <td width="150px">Field1</td>
    <td width="150px">Field2</td>
    <td width="250px">Field3</td>
   </tr>
   <tr>
    <td><input type="text" name="t1" /></td>
    <td><input type="text" name="t2" /></td>
    <td><input type="text" name="t3" /> &nbsp;&nbsp;<input type="button" value="Delete" onClick="removeRow(this);" /></td>
   </tr>
   <tr>
    <td><input type="text" name="t1" /></td>
    <td><input type="text" name="t2" /></td>
    <td><input type="text" name="t3" /> &nbsp;&nbsp;<input type="button" value="Delete" onClick="removeRow(this);" /></td>
   </tr>
   <tr>
    <td><input type="text" name="t1" /></td>
    <td><input type="text" name="t2" /></td>
    <td><input type=&quot;text" name="t3" /> &nbsp;&nbsp;<input type="button" value="Delete" onClick="removeRow(this);" /></td>
   </tr>
   <tr>
    <td><input type="text" name="t1" /></td>
    <td><input type="text" name="t2" /></td>
    <td><input type="text" name="t3" /> &nbsp;&nbsp;<input type="button" value="Delete" onClick="removeRow(this);" /></td>
   </tr>
  </table>
  <hr>
  <input type="button" value="Add Row" onClick="addRow();" />
   </body>
</html>

抱歉!评论已关闭.