日期:2014-05-16  浏览次数:20403 次

js创建表格和删除表格中的行
<script>
// 为表增加一行
function create()
{
  var tableObj = document.getElementById("tab");
  alert(tableObj.rows.length);
  var newRowObj = tableObj.insertRow(tableObj.rows.length);
 
  // 此处的顺序应该和下面的顺序一致
  var newColName = newRowObj.insertCell(newRowObj.cells.length);
  var newColGender = newRowObj.insertCell(newRowObj.cells.length);
var newColAge = newRowObj.insertCell(newRowObj.cells.length);
var newColButton=newRowObj.insertCell(newRowObj.cells.length);

newColName.innerHTML = '刘德华';
  newColGender.innerHTML = '男';
  newColAge.innerHTML = 46;
  newColButton.innerHTML = '<input type="button" value="Delete" onclick="deleteCurrentRow(this)">';
}

// 删除一行
function deleteCurrentRow(obj)
{
  var trObj = obj.parentNode.parentNode;
  var tBody = trObj.parentNode;
  tBody.removeChild(trObj);
}

</script>

<html>
<body>
<center>
<input type="button" value="create table" onclick="create()"
<div id="table"></div>
<div>
  <table id="tab">
    <tr>
        <td>姓名</td>
        <td>性别</td>
        <td>年龄</td>
        <td>操作</td>
    </tr>
  </table>
</div>
</center>
</body>
</html>