我正在使用此脚本将行插入HTML表。我之所以使用table.insert
,是因为我确实想在 HTML 页面中保留原始行,但只想添加更多行。
该表包含一个标记<tbody>
。我在最后做insertrow
函数,我应该调用哪个元素 - table
还是tbody
?换句话说,下面用于动态添加行的代码是否正确?
脚本:
var addButton=document.getElementById("add-button");
addButton.addEventListener('click', addRow, false);
function addRow(){
event.preventDefault();
var newData= document.getElementById("inputname").value;
var newLevel = document.getElementById("inputlevel").value;
console.log("new data "+newData);
console.log("new level "+newLevel);
var table = document.getElementById("mytable");
var tableLength = (table.rows.length)-1;
console.log("table lenght: "+tableLength);
var htmltext= "<tr id= 'row"+tableLength+"'> <td id='inputname"+tableLength+"'>"+newData+"</td>
<td id='inputlevel"+tableLength+"'>"+newLevel+"</td>
<td><input type='button' id='edit-button"+tableLength+"' value='Edit' class='edit' onclick='editRow("+tableLength+")'>
<input type='button' id='save-button"+tableLength+"' value='Save' class='save' onclick='saveRow("+tableLength+")'>
<input type='button' id= 'delete-button"+tableLength+"' value='Delete' class='delete' onclick='deleteRow("+tableLength+")'>
</td>
</tr>";
table.insertRow(tableLength).innerHTML=htmltext;
}//end addRow
.HTML:
<html>
<head>
<meta charset="UTF-8">
</head>
<body id="body">
<div id="wrapper">
<table align='center' cellspacing=1 cellpadding=1 id="mytable" border=1>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="text" id="inputname"></td>
<td>
<select name="levels-list" id="inputlevel">
<option value="High" id="option-1">High</option>
<option value="Mid" id="option-2">Mid</option>
<option value="Low" id="option-3">Low</option>
</select>
</td>
<td><input type="button" class="add" id="add-button" value="Add"></td>
</tr>
</tbody>
</table>
</div>
<!-- <button onclick='display()'> Display</button> -->
<script src="get-text.js"></script>
</body>
</html>
调用table
是可以的。您也可以在插入之前使用createTextNode(text)
方法。查看代码片段并查看MDN(HTMLTableElement.insertRow(((上的文档以进一步阅读:
function addRow(tableID, text) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table
var newRow = tableRef.insertRow();
// Insert a cell in the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode(text);
newCell.appendChild(newText);
}
// Call addRow(text) with the ID of a table
addRow('TableA', 'Brand new row');
addRow('TableA', 'Another new row');
<table id="TableA" border="1">
<tr>
<td>1. Old top row</td>
</tr>
<tr>
<td>2. second row</td>
</tr>
</table>