本文介绍了如何使用HTML和JavaScript在网页上创建一个可交互的表格,用户可以动态添加新行并点击按钮实现删除功能。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>表格示例</title> </head> <body> <button onclick="addRow()">添加行</button> <table id="myTable"> <tr> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> </table> <script> function addRow() { var table = document.getElementById("myTable"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); cell1.innerHTML = "张三"; cell2.innerHTML = "25"; cell3.innerHTML = "<button onclick='deleteRow(this)'>删除</button>"; } function deleteRow(btn) { var row = btn.parentNode.parentNode; row.parentNode.removeChild(row); } </script> </body> </html>