當我嘗試插入一行以清空<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>,但不是很清楚...
uj5u.com熱心網友回復:
一個表包含三個部分: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";
}
uj5u.com熱心網友回復:
var table = document.querySelector("#myTable tbody");
如果你想在 tbody 中添加一行,你可以使用,你需要像我一樣提到確切的位置document.querySelector("#myTable 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.querySelector("#myTable tbody");
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/351810.html
標籤:javascript html dom
上一篇:讓JavaScript等待元素在頁面上呈現,然后將JS物件系結到它
下一篇:js邏輯門的問題
