javascript - .insertRow() 为空时无法正常工作
问题描述
当我尝试插入一行以清空<tbody>
我的表时,它添加的行<thead>
不是空的,但不是<tbody>
.
例子:
<!DOCTYPE html>
<html>
<body>
<table id="myTable">
<thead style="background-color: red;">
<tr>
<td>A</td>
<td>B</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
</script>
</body>
</html>
编辑
解决方案:<tbody><tr></tr></tbody>
,但不是很清楚...
解决方案
一个表包含三个部分:thead、tbody和tfoot。您的代码没有理由根据需要向 tbody 插入新行。如果您想在 tbody 中添加一行,则需要提及它。在你的男女同校做一点改变:
function myFunction() {
var table = document.getElementById("myTable").getElementsByTagName('tbody')[0];
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
推荐阅读
- c - 为什么 recvfrom 通过广播 IP 没有收到数据?
- c++ - 如何构造一个具有恒定引用循环的类?
- c++ - 尝试为 gstreamer 构建 test-launch.c 但未能构建
- docker - 在 Docker 容器中安装 Kubernetes
- sql - 如何获取到今天为止 30 天内的更新记录?
- .net-5 - Visual Studio for Mac 试图在构建属性中找到 .NET Full Framework
- python - Python OpenPyxl 检测所有合并单元格时遇到问题
- c# - C# 委托和事件
- python - 按顺序对要上传的文件列表进行排序
- css - 删除左右两侧的页脚空白