javascript - javascript试图通过createelement在表格中添加html
问题描述
我的 html 文件中有一个 json 代码传入,我正在尝试通过 javascript 将表行添加到基本 .html 文件中的 html 表的顶部
这是我的javascript代码:
var data = json.data;
for (var i = 0, len = data.length; i < len; i++) {
var x = data[i];
var newItem = document.createElement("tr");
var textnode = document.innerHTML = '<th scope="row"> ' + x.granularity + '</th> <td> ' + x.instrument + '</td> <td>complete: ' + x.complete + ', type: ' + x.type + ', alerttimedate: ' + x.alerttimedate + ', firsttopbot: ' + x.firsttopbot + ', alertprice: ' + x.alertprice + ', firsttbprice: ' + x.firsttbprice + ', timestamp: ' + x.timestamp + ', proceesed: ' + x.proceesed + '</td>';
newItem.appendChild(textnode);
var list = document.getElementById("myList");
list.insertBefore(newItem, list.childNodes[0]);
}
这是html文件中的表格:
<table class="table table-striped" id="myList">
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
</table>
var textnode = document.innerHTML 内容没有向我的 html 文件添加任何元素??
有什么想法我在这里做错了吗?
json 数据来自这种格式的 php 文件
foreach ($result as $row) {
$output[] = [
'instrument' => $row['instrument'],
'granularity' => $row['granularity'],
'complete' => $row['complete'],
'type' => $row['type'],
'alerttimedate' => $row['alerttimedate'],
'firsttopbot' => $row['firsttopbot'],
'alertprice' => $row['alertprice'],
'firsttbprice' => $row['firsttbprice'],
'timestamp' => $row['timestamp'],
'proceesed' => $row['proceesed']];
$lastId = $row['id'];
}
echo json_encode([
'status' => true,
'data' => $output
]);
解决方案
由于我不确定您实际需要什么,由于缺乏编码,我为您的问题开发了一个演示(据我了解)
// Placeholder JSON data
var data = {
instrument: 'val1',
granularity: 'val2',
complete: 'val3',
type: 'val4',
alerttimedate: 'val5',
firsttopbot: 'val6',
alertprice: 'val7',
firsttbprice: 'val8',
timestamp: 'val9',
proceesed: 'val10'
}
// Select the table
var tableData = document.querySelector("#tableData")
// Creating the `tr`s
var trHead = document.createElement("tr")
var trData = document.createElement("tr")
// Add the data
for (var key in data) {
if (data.hasOwnProperty(key)) {
// Create th
var th = document.createElement("th")
th.innerText = key
// Create td
var td = document.createElement("td")
td.innerText = data[key]
// Append the `td` & `th` to the `tr`s
trHead.appendChild(th)
trData.appendChild(td)
}
}
// Append both `tr`s to the `table`
tableData.appendChild(trHead)
tableData.appendChild(trData)
table {
border: 1px solid #333;
border-collapse: collapse
}
table tr td, table tr th {
border: 1px solid #333;
padding: 5px;
}
<table id="tableData"></table>
推荐阅读
- r - 根据用户限制 SelectInput
- node.js - Webpack:未找到节点模块
- macos - 用于在 localhost 上访问 Grafana 的本地隧道
- javascript - 在 Ionic React 中使用 useIonViewDidEnter 钩子重新渲染数据
- amazon-web-services - Amazon S3,无法设置 CORS 策略
- node.js - mongodb nodejs查找没有从外部表中获取数据
- javascript - 带有时钟图形的 Javascript 计时器
- sql - 在 Azure SQL 上创建触发器
- three.js - 如何最好地表示渐变镜片?
- wolfram-mathematica - Mathematica 上的递归函数