在JavaScript中,如何动态地向表中添加行?在JavaScript事件上,我想创建一个类似的行并附加到表中.
Sim*_*ver 40
如果你不想使用jQuery,有一对夫妇,你可以使用,喜欢简单的功能cloneNode(),createElement()和appendChild().这是一个简单的演示,它使用clone或create方法将一行附加到表的末尾.在IE8和FF3.5中测试过.
<html>
<head>
<script type="text/javascript">
function cloneRow() {
var row = document.getElementById("rowToClone"); // find row to copy
var table = document.getElementById("tableToModify"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function createRow() {
var row = document.createElement('tr'); // create row node
var col = document.createElement('td'); // create column node
var col2 = document.createElement('td'); // create second column node
row.appendChild(col); // append first column to row
row.appendChild(col2); // append second column to row
col.innerHTML = "qwe"; // put data in first column
col2.innerHTML = "rty"; // put data in second column
var table = document.getElementById("tableToModify"); // find table to append to
table.appendChild(row); // append row to table
}
</script>
</head>
<body>
<input type="button" onclick="cloneRow()" value="Clone Row" />
<input type="button" onclick="createRow()" value="Create Row" />
<table>
<tbody id="tableToModify">
<tr id="rowToClone">
<td>foo</td>
<td>bar</td>
</tr>
</tbody>
</table>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
小智 12
今天尝试了各种各样的搜索,利用了来源:http://www.mredkj.com/tutorials/tablebasics3.html和http://www.mredkj.com/tutorials/tableaddcolumn.html
这是我的逻辑研究的结果,它现在正在运作
function addRow(id)
{ var x=document.getElementById(id).tBodies[0]; //get the table
var node=t.rows[0].cloneNode(true); //clone the previous node or row
x.appendChild(node); //add the node or row to the table
}
function delRow(id)
{ var x=document.getElementById(id).tBodies[0]; //get the table
x.deleteRow(1); //delete the last row
}
Run Code Online (Sandbox Code Playgroud)
注1:我的表包含一个单元格,每个表行(tr)有一个文本框+一个标签.
注2:连续,有多个(td)有标签+文本框
小智 6
我知道这是一篇旧帖子,但我觉得以下代码可以帮助其他读者
$("button").click(function () {
$("#DataRow").clone().appendTo("#mainTable");
});
Run Code Online (Sandbox Code Playgroud)