创建表行的克隆并在JavaScript中附加到表 [英] Create clone of table row and append to table in JavaScript
本文介绍了创建表行的克隆并在JavaScript中附加到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript中,如何动态地向表中添加行?在JavaScript事件上,我想创建一个类似的行并追加到表中。
In JavaScript, how can I add a row dynamically to a table? On a JavaScript event I want to create a similar row and append to the table.
推荐答案
如果你不想使用jQuery,你可以使用几个简单的函数,比如 cloneNode()
, createElement()
和的appendChild()
。这是一个简单的演示,它使用clone或create方法将一行附加到表的末尾。在IE8和FF3.5中测试。
If you don't wish to use jQuery, there are a couple of simple functions you could use, like cloneNode()
, createElement()
and appendChild()
. Here is a simple demonstration that appends a row to the end of the table using either the clone or create method. Tested in IE8 and 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>
这篇关于创建表行的克隆并在JavaScript中附加到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文