<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function () { //1.获取元素 var inps = document.querySelectorAll("input"); var tab = document.querySelector("table"); //获取原本存在的删除按钮 var dels = tab.querySelectorAll("button"); function a(){ this.parentNode.parentNode.remove(); } //给每一个删除按钮添加点击事件 for(var i=0; i<dels.length; i++){ dels[i].onclick = a } //2.点击 按钮 获取input中输入的内容 追加到table中 inps[3].onclick = function () { var name = inps[0].value; var gender = inps[1].value; var age = inps[2].value; //3.创建 一个 tr var tr = document.createElement("tr"); tr.appendChild(createE("td", tab.tBodies[0].rows.length + 1));//id tr.appendChild(createE("td", name)); tr.appendChild(createE("td", gender)); tr.appendChild(createE("td", age)); tr.appendChild(createE("td","<button>删除</button>")); //需要给删除按钮 添加 点击事件 删除一行 var del = tr.querySelector("button"); del.onclick = a //将tr追加到 tbody中 tab.tBodies[0].appendChild(tr); inps[0].value = inps[1].value = inps[2].value = ""; } //封装一个 创建元素的函数 function createE(tagName, value) {//标签名 内容 //1.主要代码 var ele = document.createElement(tagName); ele.innerHTML = value; return ele; } } </script> </head> <body> <input type="text" placeholder="请输入姓名"> <input type="text" placeholder="请输入性别"> <input type="text" placeholder="请输入年龄"> <input type="button" value="添加"> <table width="500" border="1"> <thead> <tr> <td>id</td> <td>姓名</td> <td>性别</td> <td>年龄</td> <td>操作</td> </tr> </thead> <tbody> <tr> <td>1</td> <td>tom</td> <td>男</td> <td>18</td> <td><button>删除</button></td> </tr> <tr> <td>2</td> <td>jack</td> <td>男</td> <td>20</td> <td><button>删除</button></td> </tr> <tr> <td>3</td> <td>rose</td> <td>女</td> <td>18</td> <td><button>删除</button></td> </tr> </tbody> </table> </body> </html>