js实现动态表格的添加
<!DOCTYPE html> <html lang="en"> <head> <title>Table_Simple CSS for HTML tables</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> html { font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } body { margin: 10px; } table { border-collapse: collapse; border-spacing: 0; } td,th { padding: 0; } .pure-table { border-collapse: collapse; border-spacing: 0; empty-cells: show; border: 1px solid #cbcbcb; } .pure-table caption { color: #000; font: italic 85%/1 arial,sans-serif; padding: 1em 0; text-align: center; } .pure-table td,.pure-table th { border-left: 1px solid #cbcbcb; border-width: 0 0 0 1px; font-size: inherit; margin: 0; overflow: visible; padding: .5em 1em; } .pure-table thead { background-color: #e0e0e0; color: #000; text-align: left; vertical-align: bottom; } .pure-table td { background-color: transparent; } div.jizhong{ text-align: center; } </style> </head> <body> <div class="jizhong"> <input type="text" id="name">姓名<input type="text" id="age">年龄<input type="text" id="gender">性别 <button id="add">添加</button> </div> <table class="pure-table" id="tb" align="center"> <caption>学生信息表</caption> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>王敬博</td> <td>18</td> <td>男</td> <td><a href="JavaScript:void(0)" onclick="drop(this)">删除</a></td> </tr> <tr> <td>江银涛</td> <td>20</td> <td>女</td> <td><a href="JavaScript:void(0)" onclick="drop(this)">删除</a></td> </tr> </tbody> </table> <script> //1 为添加按钮绑定单击事件 document.getElementById("add").onclick = function(){ //2创建行元素 let tr = document.createElement("tr"); //3创建四个单元格元素 let nameTd = document.createElement("td"); let ageTd = document.createElement("td"); let genderTd = document.createElement("td"); let deleteTd = document.createElement("td"); //4将td添加到tr中 tr.appendChild(nameTd); tr.appendChild(ageTd); tr.appendChild(genderTd); tr.appendChild(deleteTd); //5获取文本框的输入信息 let name = document.getElementById("name").value; let age = document.getElementById("age").value; let gender = document.getElementById("gender").value; //6将文本框信息创建三个文本元素 let nameText = document.createTextNode(name); let ageText = document.createTextNode(age); let genderText = document.createTextNode(gender); //7将三个文本元素添加到td中 nameTd.appendChild(nameText); ageTd.appendChild(ageText); genderTd.appendChild(genderText); //8创建超链接元素和显示的文本及添加href属性 let a = document.createElement("a"); let aText = document.createTextNode("删除"); a.setAttribute("href","JavaScript:void(0)"); a.setAttribute("onclick","drop(this)") a.appendChild(aText); //9将超链接元素添加到td中 deleteTd.appendChild(a); //10获取表格元素,将添加到table中 let table = document.getElementById("tb"); table.appendChild(tr); } function drop(obj){ //1获取table元素 let table = obj.parentElement.parentElement.parentElement; //2获取tr元素 let tr = obj.parentElement.parentElement; //3删除tr table.removeChild(tr); } </script> </body> </html>