我正在尝试在纯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>&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不是函数
答案 0 :(得分:4)
那是因为你的tbody
实际上是一个类似数组的对象,就像在[<tbody>]
中一样:
var tbody = (...).getElementsByTagName("TBODY");
您正在使用“获取元素”,它会返回一个节点列表。拿第一个:
var tbody = (...).getElementsByTagName("TBODY")[0];
答案 1 :(得分:2)
var tbody = document.getElementsByClassName('table1_out').getElementsByTagName("TBODY");
引用节点列表。
你需要这样做:
var tbody = document.getElementsByClassName('table1_out').getElementsByTagName("TBODY")[0];