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

JS对表格的动态增加删除行 (多个demo)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>动态增加和删除表格行</title>

<script type="text/javascript">
window.onload = function addRow() {
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;

var nameText = document.createTextNode(name); //创建文本节点
var ageText = document.createTextNode(age);

var nameTd = document.createElement("td"); //创建td节点
var ageTd = document.createElement("td");

var tr = document.createElement("tr"); //创建tr节点
nameTd.appendChild(nameText);
ageTd.appendChild(ageText);

tr.appendChild(nameTd);
tr.appendChild(ageTd);

var tbody = document.getElementById("tbody");
tbody.appendChild(tr);
}

function delRow() {
var objTbody = document.getElementById("tbody");
objTbody.removeChild(objTbody.lastChild); //删除最后一个子节点,因为表格每删除一行行号会自动发生变化。所以每次从最后删除
}
</script>
</head>

<body>
<table id="t1" border="1">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>name1</td>
<td>25</td>
</tr>
<tr>
<td>name2</td>
<td>26</td>
</tr>
</tbody>
</table>
<hr>

Name:<input type="text" id="name" />Age:<input type="text" id="age" />
<input type="button" value="add" onclick="addRow()"/>
<input type="button" value="del" onclick="delRow()"/>
</body>

</html>