当我尝试调用api并将数据加载到表中时,数据会添加到同一行中。但是每个数据都应添加到单独的行中。顺便说一句,我只有一个<td>
我该如何解决这个问题?
HTML:
<table class="table table-striped table-bordered" id="editable-datatable">
<thead>
<tr>
<th class="footable-sortable"> Host
<span class="footable-sort-indicator"></span>
</th>
</tr>
</thead>
<tbody class="text-center" id="concat_here">
<tr>
<td id="row1">
</td>
</tr>
</span>
</tbody>
</table>
JS:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
obj = JSON.parse(xmlhttp.responseText);
list_length = obj.log_ast.length;
var i=0;
for(i=0; i<list_length; i++)
{
document.getElementById('row1').innerHTML = document.getElementById('row1').innerHTML+'<tr>'+'<td>'+obj.log_ast[i].address+'</td>'+'</tr>';
}
}
答案 0 :(得分:1)
“正确的方法”是使用
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow
var table = document.getElementById("editable-datatable")
var row = table.insertRow()
然后使用
将单元格添加到行中https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell
var cell = row.insertCell()
然后使用将文本添加到单元格
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
cell.innerText = obj.log_ast[i].address
答案 1 :(得分:0)
我想您正在寻找的正是此代码段。
HTML
<table class="table table-striped table-bordered" id="editable-datatable">
<thead>
<tr>
<th class="footable-sortable"> Host
<span class="footable-sort-indicator"></span>
</th>
</tr>
</thead>
<tbody class="text-center" id="concat_here">
</span>
</tbody>
</table>
JS
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
obj = JSON.parse(xmlhttp.responseText);
list_length = obj.log_ast.length;
var i=0;
for(i=0; i<list_length; i++)
{
var htmlContent = '<td>'+obj.log_ast[i].address+'</td>';
var refTbl = document.getElementById('editable-datatable').getElementsByTagName('tbody')[0];
var newRow = refTbl.insertRow(refTbl.rows.length);
newRow.innerHTML = htmlContent
}
}