我在向表中添加新行时遇到了问题。 问题是新行被添加到blcok中而不是阻塞。
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}

table{
border: 1px solid #ccc;
}

<table id="myTable">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
</tr>
</thead>
<tbody>
//new row is supposed to add into here.
<tbody>
</table>
<br>
<button onclick="myFunction()">Try it</button>
&#13;
感谢您的帮助。
答案 0 :(得分:1)
您想要向tbody
添加新行,因此请先使用getElementsByTagName("tbody")
选择tbody。也可以使用insertRow(0)
代替insertRow(1)
function myFunction() {
var table = document.getElementById("myTable");
var tbody = table.getElementsByTagName('tbody');
console.log(tbody)
var row = tbody[0].insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
table{
border: 1px solid #ccc;
}
<table id="myTable">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
</tr>
</thead>
<tbody>
//new row is supposed to add into here.
<tbody>
</table>
<br>
<button onclick="myFunction()">Try it</button>