Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - javascript在具有2个标题的表中插入新行(javascript Insert a new row in a table with 2 headers)

I have a table that looks like this :(我有一个看起来像这样的表:)

<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> And I am trying to create a javascript function to add new rows to the table that would match the last row.(我正在尝试创建一个javascript函数,以向表中添加与最后一行匹配的新行。) <script> function addRow() { var table = document.getElementById("mytable"); var rows = table.getElementsByTagName("tr").length; var row = table.insertRow(rows); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); cell1.innerHTML = "header"; cell2.innerHTML = "cell1"; cell3.innerHTML = "cell2"; } </script> After spending a good amount of time on google trying to figure it out.(在Google上花费了大量时间后试图找出答案。) I must say I could not find what I am looking for.(我必须说我找不到我想要的东西。) Any help would be much appreciated.(任何帮助将非常感激。)   ask by L. Ouellet translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...