我克隆一行并将其附加到以下函数 add_record() 的表末尾。 我的问题是如何将其附加到表的开头。 我尝试使用
$("#main_table_id tbody").prepend(clone)
和
$("#main_table_id tbody").prepend(clone.innerHtml)
但是没有成功。
function add_record(){
var row = document.getElementById("template_no_1_id");
var table = document.getElementById("main_table_id");
var clone = row.cloneNode(true);
clone.id = "newID";
table.appendChild(clone);
}
最佳答案
使用 native 函数 insertRow。
<table id="TableA">
<tr>
<td>Old top row</td>
</tr>
</table>
<script type="text/javascript">
function addRow(tableID) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New top row');
newCell.appendChild(newText);
}
// Call addRow() with the ID of a table
addRow('TableA');
</script>
信用:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement.insertRow
关于javascript - 如何使用 javascript 将行添加到表的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258077/