gpt4 book ai didi

javascript - 如何使用 DOM 将一行附加到 html 表?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:05 24 4
gpt4 key购买 nike

我正尝试在纯 JS 中向 HTML 表格添加一行,如下所示,

    var tbody = document.getElementsByClassName('table1_out').getElementsByTagName("TBODY");
var row = document.createElement("TR");

var td1 = document.createElement("TD")
var strHtml1 = "<?php echo $addNewCurrencyPOST["id"] ?>";
td1.innerHTML = strHtml1;

var td2 = document.createElement("TD")
var strHtml2 = "<div class='led on'></div>";
td2.innerHTML = strHtml2;

var td3 = document.createElement("TD")
var strHtml3 = "<?php echo $addNewCurrencyPOST["symbol"] ?>";
td3.innerHTML = strHtml3;

var td4 = document.createElement("TD")
var strHtml4 = "<?php echo $addNewCurrencyPOST["symbolhtml"] ?>";
td4.innerHTML = strHtml4;

var td5 = document.createElement("TD")
var strHtml5 = "<?php echo $addNewCurrencyPOST["usdrate"] ?>";
td5.innerHTML = strHtml5;

var td6 = document.createElement("TD")
var strHtml6 = "<?php echo $addNewCurrencyPOST["eurrate"] ?>";
td6.innerHTML = strHtml6;

var td7 = document.createElement("TD")
var strHtml7 = '';
td7.innerHTML = strHtml7;

// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
row.appendChild(td7);

// append row to table
tbody.appendChild(row);

这是表的结构,

<div class="table1_out">
<table>
<thead>
<tr>
<th>Id</th>
<th>Status</th>
<th>Symbol</th>
<th>Symbol html</th>
<th>Exchange rate EUR</th>
<th>Exchange rate USD</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>EUR</td>
<td><div class="led on"></div></td>
<td>€</td>
<td>&amp;euro;</td>
<td>1</td>
<td>1.319810</td>
<td><input type="button" value="Edit" onclick="document.location.href='/backoffice_dev.php/currency/edit/EUR';"></td>
</tr> </tbody>
</table>
</div>

但它抛出错误:

TypeError: tbody.appendChild is not a function

最佳答案

那是因为你的 tbody实际上是一个类似数组的对象,如 [<tbody>] :

var tbody = (...).getElementsByTagName("TBODY");

您正在使用“get Elements”,它会返回一个节点列表。采取其中的第一个:

var tbody = (...).getElementsByTagName("TBODY")[0];

关于javascript - 如何使用 DOM 将一行附加到 html 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067769/

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