完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>在表格的最后一行之前插入一行</title> <script> count = 0;
function insertRowBeforeLastRow(tableID) { var table = document.getElementById(tableID); var row = table.insertRow(table.rows.length - 1); for (var i = 0; i < table.rows[0].cells.length; i++) { var cell = row.insertCell(i); cell.innerHTML = "New_" + count++; } } </script> </head> <body> <h2>在表格的最后一行之前插入一行</h2> <table id="myTable" border="1"> <tr> <th>账号</th> <th>姓名</th> <th>密码</th> </tr> <tr> <td>B100</td> <td>小王</td> <td>123</td> </tr> </table> <br> <button type="button" onclick="insertRowBeforeLastRow('myTable')">插入新行</button> </body> </html>
|
代码解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| count = 0;
function insertRowBeforeLastRow(tableID) { var table = document.getElementById(tableID); var row = table.insertRow(table.rows.length - 1); for (var i = 0; i < table.rows[0].cells.length; i++) { var cell = row.insertCell(i); cell.innerHTML = "New_" + count++; } }
|
参考资料
https://www.runoob.com/jsref/dom-obj-table.html
https://www.runoob.com/jsref/coll-table-rows.html
https://www.runoob.com/jsref/coll-table-rows.html
https://www.runoob.com/jsref/met-table-insertrow.html
https://www.runoob.com/try/try.php?filename=tryjsref_table_insertrow
https://www.runoob.com/try/try.php?filename=try_dom_tablerow_insertcell