[英]Why is my function saying that a promise isn't being handled correctly?
[英]Why isn't this table being sorted correctly?
不知道为什么表没有被正确地排序到行和列中。 我正在尝试创建一个二维数组,然后使用嵌套的 for 循环来自动创建一个表。
list = [ [12, 4, 22], [11, 32, 7], [9, 16, 13] ]; for (var i = 0; i < list.length; i++) { tablebody.innerHTML += "<tr>"; for (var j = 0; j < list[i].length; j++) { tablebody.innerHTML += "<td>" + list[i][j] + "</td>"; } tablebody.innerHTML += "</tr>" }
body { background-color: black; color: white; }
<table id="table"> <thead id="tablehead"> <tr>List[0]</tr> <tr>List[1]</tr> <tr>List[2]</tr> </thead> <tbody id="tablebody"> </tbody> </table>
您不能向innerHTML
添加片段。 当你做tablebody.innerHTML+="<tr>";
, 浏览器会在后面自动添加一个结束</tr>
。
您需要将字符串构建到自己的变量中,然后执行tablebody.innerHTML = yourTableVar;
然后。
var tableData = '';
for (var i = 0; i < list.length; i++) {
tableData += "<tr>";
for (var j = 0; j < list[i].length; j++) {
tableData += "<td>" + list[i][j] + "</td>";
}
tableData += "</tr>"
}
tablebody.innerHTML = tableData;
此外,您的<thead>
HTML 不正确。 你需要有一个<tr>
作为你的标题行和<th>
标签与你的列标题:
<thead id="tablehead">
<tr>
<th>List[0]</th>
<th>List[1]</th>
<th>List[2]</th>
</tr>
</thead>
const tablebody = document.querySelector('table#table tbody') , list = [ [ 12, 4, 22 ] , [ 11, 32, 7 ] , [ 9, 16, 13 ] ] for (let row of list) { let nRow = tablebody.insertRow() for( let vCol of row) { nRow.insertCell().textContent = vCol } }
body { background-color : black; color : white; } table { border-collapse : collapse; } table td { padding : 5px; width : 20px; height : 20px; border : 1px solid green; text-align : center; } table thead { background-color : darkblue; }
<table id="table"> <thead> <tr> <td>List[0]</td> <td>List[1]</td> <td>List[2]</td> </tr> </thead> <tbody> </tbody> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.