<!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> /* 删除tr的响应函数 */ function delA() { var tr = this.parentNode.parentNode; var name = tr.children[0].innerHTML; var flag = confirm("确定" + name + "删除吗?"); if (flag) { tr.parentNode.removeChild(tr); } return false; }; window.onload = function () { var allA = document.getElementsByTagName("a"); for (var i = 0; i < allA.length; i++) { allA[i].onclick = delA; } /* ------------------------------------------------------------------------------ 添加员工的功能 -点击按钮以后,将员工的信息添加到表格中 */ // 为提交按钮绑定一个单击响应函数 var addEmpButton = document.getElementById("addEmpButton"); addEmpButton.onclick = function () { // alert("hello");//测试 //获取用户添加的员工信息 // 获取员工的名字 var name = document.getElementById("empName").value; // 获取员工的email和salary var email = document.getElementById("email").value; var salary = document.getElementById("salary").value; // alert(name+","+email+","+salary); // 需要将将获取到的信息保存到tr中 // 创建一个tr var tr = document.createElement("tr"); // 设置tr中的内容 tr.innerHTML="<td>"+name+"</td>"+ "<td>"+email+"</td>" + "<td>"+salary+"</td>" + "<td><a href='javascript:;'>Delete</a></td>" ; // 获取刚刚添加的a元素,并为其绑定单击响应函数 var a=tr.getElementsByTagName("a")[0]; a.onclick=delA; // 获取table var employeeTable = document.getElementById("employeeTable"); // 获取employeeTable中的tbody var tbody = employeeTable.getElementsByTagName("tbody")[0]; // 将tr添加到tbody中 tbody.appendChild(tr); // tbody.innerHTML +="<tr>"+ // "<td>" + name + "</td>" + // "<td>" + email + "</td>" + // "<td>" + salary + "</td>" + // "<td><a href='javascript:;'>Delete</a></td>" // +"</tr>"; }; }; </script> </head> <body> <table id="employeeTable"> <tr> <th>Name</th> <th>Email</th> <th>Salary</th> <th> </th> </tr> <tr> <td>Tom</td> <td>tom@tom.com</td> <td>5000</td> <!-- <td><a href="deleteEmp?id=001">Delete</a></td> --> <td><a href="javascript:;">Delete</a></td> <!--等价于return false;--> </tr> <tr> <td>Jerry</td> <td>Jerryierry@sohu.com</td> <td>8000</td> <td><a href="deleteEmp?id=002">Delete</a></td> </tr> <tr> <td>Bob</td> <td>bob@tom.com</td> <td>10000</td> <td><a href="deleteEmp?id=003">Delete</a></td> </tr> </table> <div> <h4>添加新员工</h4> <table> <tr> <td class="word">name:</td> <td class="inp"> <input type="text" name="empName" id="empName" /> </td> </tr> <tr> <td class="word">email:</td> <td class="inp"> <input type="text" name="email" id="email" /> </td> </tr> <tr> <td class="word">salary:</td> <td class="inp"> <input type="text" name="salary" id="salary" /> </td> </tr> <tr> <td colspan="2" align="center"> <button id="addEmpButton" value="abc"> Submit </button> </td> </tr> </table> </div> </body> </html>