Your problem is that insertCell()
only creates <td>
tags, so you need to use document.createElement
to create the <th>
tag for your first cell.(您的问题是insertCell()
仅创建<td>
标签,因此您需要使用document.createElement
为<th>
一个单元格创建<th>
标签。)
<button onclick="addRow()">Add a Row</button> <table id="mytable"> <tr> <th colspan="3">My header</th> <tr> <tr> <th>header</th> <td>cell1</td> <td>cell2</td> </tr> </table> <script> function addRow() { var table = document.getElementById("mytable"); var rows = table.getElementsByTagName("tr").length; var row = table.insertRow(rows); var cell1 = document.createElement("TH"); row.appendChild(cell1); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); cell1.innerHTML = "header"; cell2.innerHTML = "cell1"; cell3.innerHTML = "cell2"; } </script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…