要在单元格中创建新行而不是替换值,可以使用innerHTML
属性将新的HTML代码插入到单元格中。
以下是一个示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Create New Row in Table Cell</title>
</head>
<body>
<table id="myTable">
<tr>
<td id="myCell">Initial Value</td>
</tr>
</table>
<script>
// 获取单元格元素
var cell = document.getElementById("myCell");
// 创建新的行
var newRow = document.createElement("tr");
// 创建新的单元格
var newCell = document.createElement("td");
newCell.innerHTML = "New Value";
// 将新的单元格添加到新的行
newRow.appendChild(newCell);
// 将新的行添加到表格中的单元格
cell.appendChild(newRow);
</script>
</body>
</html>
上述代码将在表格的单元格中创建一个新的行,并将新的单元格添加到该行中。请注意,通过innerHTML
属性,可以在新的单元格中插入任何有效的HTML代码,而不仅限于纯文本。