正如您从屏幕截图中看到的:
每个元素都被放入自己的 tr 中。
我不希望这样,我只是希望每个元素都在 td 中,然后用一个 tr 包围所有元素
HTML:
<div id='result'>
<table class='table'>
<thead>
<tr><th>Question</th><th>Animal</th><th>Expected</th><th>You Picked</th><th>Result</th></tr>
</thead>
<tbody id='result-table'>
</tbody>
</table>
</div>
Javascript:
function displayResult() {
let tableDisplay = document.getElementById("result-table")
let theResult = document.getElementById("result")
theResult.style.display = "block"
for(let i = 0; i<qArr.length; i++){
tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + qArr[i] + `</td>`
}
// qArr.forEach(x => {
// tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
// })
}
最佳答案
td
不能是 tbody
的子级,只能是 tr
的子级。因为浏览器独立添加这个元素。您需要将数据添加到结果行
。
<tbody id='result-table'>
<tr id='result-row'></tr>
</tbody>
顺便说一句,与 DOM 交互是一项昂贵的操作。最好先组成一个数组,然后插入一次。
关于Javascript 会自动将 <tr> 添加到我的表格元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017591/