<!DOCTYPE >
<html>
<head>
<meta charset=UTF-8">
<title>DOM增删表格中的元素</title>
<link rel="stylesheet" type="text/css" href="ex_2_style/css.css" />
<script type="text/javascript">
window.onload = function(){
function aDelete(){
//获取tr元素节点
var trEle = this.parentNode.parentNode;
//获取td元素节点
var tdEle=trEle.getElementsByTagName("td");
//获取每条记录中的name
var name=tdEle[0].innerHTML;
//弹出确认删除框
var flag=confirm("确定删除"+name+"吗?");
//删除tr元素节点
if(flag){
trEle.parentNode.removeChild(trEle);
}
return false;
}
//删除操作
//获取对象按钮
var aEle=document.getElementsByTagName("a");
for(var i =0;i<aEle.length;i++){
aEle[i].onclick=aDelete;
}
//添加操作
//获取提交按钮
/*1.给sumbit绑定单机事件*/
var addEmpButton=document.getElementById("addEmpButton");
addEmpButton.onclick=function(){
/*2.获取用户在表单中输入的内容*/
var empNameText =document.getElementById("empName").value;
var emailText =document.getElementById("email").value;
var salaryText =document.getElementById("salary").value;
/*3.根据文本内容创建节点*/
var nmText =document.createTextNode(empNameText);
var emText =document.createTextNode(emailText);
var slText =document.createTextNode(salaryText);
var dlText=document.createTextNode("Delete");
//创建a元素节点
var aEle =document.createElement("a");
aEle.href="#";
aEle.onclick=aDelete;
/*4:创建对应的td元素节点*/
var nmTd =document.createElement("td");
var emTd =document.createElement("td");
var slTd =document.createElement("td");
var dlTd =document.createElement("td");
/* 5:td和文本节点组装(在创建最后一个td的时候里面还需要有a元素节点并且需要组装)*/
nmTd.appendChild(nmText);
emTd.appendChild(emText);
slTd.appendChild(slText);
aEle.appendChild(dlText)
dlTd.appendChild(aEle)
/*6:创建tr节点,并且需要和td组装*/
var trEle =document.createElement("tr");
trEle.appendChild(nmTd);
trEle.appendChild(emTd);
trEle.appendChild(slTd);
trEle.appendChild(dlTd);
/*7.将tr与table组装*/
var tableEle =document.getElementById("employeeTable");
tableEle.appendChild(trEle);
}
};
</script>
</head>
<body>
<table id="employeeTable">
<tr>
<th>Name</th>
<th>Email</th>
<th>Salary</th>
<th> </th>
</tr>
<tr>
<td>Tom</td>
<td></td>
<td>5000</td>
<td><a href="deleteEmp?id=001">Delete</a></td>
</tr>
<tr>
<td>Jerry</td>
<td></td>
<td>8000</td>
<td><a href="deleteEmp?id=002">Delete</a></td>
</tr>
<tr>
<td>Bob</td>
<td></td>
<td>10000</td>
<td><a href="deleteEmp?id=003">Delete</a></td>
</tr>
</table>
<div id="formDiv">
<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>