结构:
<table border="1">
<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="javascript:;">Delete</a></td>
</tr>
<tr>
<td>Jerry</td>
<td>jerry@sohu.com</td>
<td>8000</td>
<td><a href="javascript:;">Delete</a></td>
</tr>
<tr>
<td>Bob</td>
<td>bob@tom.com</td>
<td>10000</td>
<td><a href="javascript:;">Delete</a></td>
</tr>
</table>
<form action="#">
<h4>添加新员工</h4>
<div class="row">
name: <input type="text" name="name" id="name"><br>
email: <input type="text" name="email" id="email"><br>
salary: <input type="text" name="salary" id="salary">
</div>
<button id="btn">Submit</button>
</form>
js:
function delLin(){
var tr1=this.parentNode.parentNode;
var del=confirm("确认要删除"+tr1.children[0].innerText+"吗?")
if(del){
tr1.parentNode.removeChild(tr1)
}
}
// 删除
var Alla=document.getElementsByTagName("a");
for(var i=0;i<Alla.length;i++){
Alla[i].onclick=delLin;
}
// 添加
var name=document.getElementById("name");
var email=document.getElementById("email");
var salary=document.getElementById("salary");
var btn=document.getElementById("btn");
var tBody=document.getElementsByTagName("tbody")[0];
btn.onclick=function(){
var tr=document.createElement("tr");
tr.innerHTML="<td>"+name.value+"</td>"+
"<td>"+email.value+"</td>"+
"<td>"+salary.value+"</td>"+
"<td><a href='javascript:;'>Delete</a></td>";
tBody.appendChild(tr);
var a=tr.getElementsByTagName("a")[0];
a.onclick=delLin;
return false;
}