gpt4 book ai didi

javascript - 将行添加到现有表中

转载 作者:行者123 更新时间:2023-12-02 14:25:51 25 4
gpt4 key购买 nike

我可以知道如何将项目插入到我的表格主体中吗?我的代码似乎不起作用。

var tableRef = document.getElementById("myList").getElementsByTagName("tbody");

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = tableRef.insertCell(0);

var myTextTwo = "hello world";

var newText = document.createTextNode(myTextTwo);

newCell.appendChild(newText);
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>

</tbody>
</table>

最佳答案

getElementsByTagName 返回一个数组。您需要附加 [0] 以选择数组中的第一个元素。

您还尝试在 tableRef 上使用 insertCell,而您应该在 newRow 上使用它:

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = newRow.insertCell(0);

var myTextTwo = "hello world";

var newText = document.createTextNode(myTextTwo);

newCell.appendChild(newText);
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>

</tbody>
</table>

关于javascript - 将行添加到现有表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38248717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com