猿问

为什么这个表没有正确排序?

不知道为什么表格没有正确排序为行和列。我试图创建一个二维数组,然后使用嵌套 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>


拉风的咖菲猫
浏览 88回答 2
2回答

慕村225694

您无法将片段添加到innerHTML. 当您这样做时tablebody.innerHTML+="<tr>";,浏览器会自动</tr>在后面添加一个结束语。您需要将字符串构建到它自己的变量中,然后tablebody.innerHTML = yourTableVar;再执行。var tableData = '';for (var i = 0; i < list.length; i++) {&nbsp; tableData += "<tr>";&nbsp; for (var j = 0; j < list[i].length; j++) {&nbsp; &nbsp; tableData += "<td>" + list[i][j] + "</td>";&nbsp; }&nbsp; tableData += "</tr>"}tablebody.innerHTML = tableData;另外,您的 HTML<thead>不正确。您需要有一个<tr>作为标题行和<th>带有列标题的标签:<thead id="tablehead">&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <th>List[0]</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>List[1]</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>List[2]</th>&nbsp; &nbsp; </tr></thead>

慕容708150

const tablebody = document.querySelector('table#table tbody')&nbsp; ,&nbsp; &nbsp;list =&nbsp; &nbsp; &nbsp; &nbsp;[ [ 12,&nbsp; 4, 22 ]&nbsp; &nbsp; &nbsp; &nbsp;, [ 11, 32,&nbsp; 7 ]&nbsp; &nbsp; &nbsp; &nbsp;, [&nbsp; 9, 16, 13 ]&nbsp; &nbsp; &nbsp; &nbsp;]for (let row of list)&nbsp;&nbsp; {&nbsp; let nRow = tablebody.insertRow()&nbsp; for( let vCol of row)&nbsp; &nbsp; {&nbsp; &nbsp; nRow.insertCell().textContent = vCol&nbsp; &nbsp; }&nbsp; }body {&nbsp; background-color : black;&nbsp; color&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : white;&nbsp; }table&nbsp; {&nbsp; border-collapse&nbsp; : collapse;&nbsp; }table td {&nbsp; padding&nbsp; &nbsp; : 5px;&nbsp; width&nbsp; &nbsp; &nbsp; : 20px;&nbsp; height&nbsp; &nbsp; &nbsp;: 20px;&nbsp; border&nbsp; &nbsp; &nbsp;: 1px solid green;&nbsp; text-align : center;&nbsp; }table thead {&nbsp; background-color : darkblue;&nbsp; }<table id="table">&nbsp; <thead>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td>List[0]</td>&nbsp; &nbsp; &nbsp; <td>List[1]</td>&nbsp; &nbsp; &nbsp; <td>List[2]</td>&nbsp; &nbsp; </tr>&nbsp; </thead>&nbsp; <tbody>&nbsp; </tbody></table>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答