我发现了一些似乎使用jquery解决这个问题的其他帖子,但我想只使用javascript。我想使用bootstrap创建一个表,但似乎无法弄清楚如何将新数据附加到表。它正在创建标题,但只是将我想要的项目转储为表头下面的行。
HTML
<div id = specificFailureCountTable-js></div>
JS
let filterText = 'machines';
let tableData = document.getElementById("specificFailureCountTable-js");
let data = [["machineA",15],["machineB",54],["machineC",26]];
//set header of table
tableData.innerHTML = `
<table class="table table-striped" id = "myTable">
<thead>
<tr>
<th scope="col">${filterText}</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
`;
//create//append rows
for(i = 0; i < data.length; i++){
tableData.innerHTML = tableData.innerHTML +
`<tr>
<th scope="row">${i}</th>
<td>${data[i][0]}</td>
<td>${data[i][1]}</td>
</tr>`
}
//close off table
tableData.innerHTML = tableData.innerHTML +
`</tbody>
</table>`
;
只需使用将定义表附加到该变量的变量,最后将它准备好分配给tableData.innerHTML
,否则你将破坏DOM(不确定输出是什么,但根据浏览器可能会有所不同):
let filterText = 'machines';
let tableData = document.getElementById("specificFailureCountTable-js");
let data = [["machineA",15],["machineB",54],["machineC",26]];
//set header of table
let table = `
<table class="table table-striped" id = "myTable">
<thead>
<tr>
<th scope="col">${filterText}</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
`;
//create//append rows
for(i = 0; i < data.length; i++){
table = table +
`<tr>
<th scope="row">${i}</th>
<td>${data[i][0]}</td>
<td>${data[i][1]}</td>
</tr>`
}
//close off table
table = table +
`</tbody>
</table>`
;
tableData.innerHTML = table;
另一方面说明:你可以使用table += 'xxx'
作为table = table + 'xxx'
的捷径