<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<style type="text/css">
tr:hover{
background-color:#eee;
}
</style>
<script type="text/javascript">
window.onload = function(){
//删除操作
deleteRow();
}
//编写添加函数
function addRow(){
var table = document.getElementsByTagName("tbody")[0];
var num = document.getElementsByName("number")[0];
var name = document.getElementsByName("name")[0];
//console.log(name.value);
if(num.value && name.value){
var newTr = document.createElement("tr");
newTr.innerHTML = "<td>"+num.value+"</td><td>"+name.value+"</td><td><a href='javascript:;' >删除</a></td>";
// console.log(newTr);
table.appendChild(newTr);
deleteRow();
}else{
alert("请输入完整信息!");
}
}
//编写删除函数
function deleteRow(){
var tr = document.getElementsByTagName("tr"),
a = document.getElementsByTagName("a");
for(var i=0;i<a.length;i++){
a[i].index = i;
a[i].onclick=function(){
//console.log(this.index);
tr[0].parentNode.removeChild(tr[this.index+1]);
//console.log(this.index);
deleteRow();
}
}
}
</script>
</head>
<body>
<table border="1" width="50%" id="table">
<tr>
<th>学号</th>
<th>姓名</th>
<th>操作</th>
</tr>
<tr>
<td>xh001</td>
<td>王小明</td>
<td><a href="javascript:;" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh003</td>
<td>张小三</td>
<td><a href="javascript:;" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<br/>
<label>学号</label>
<input type="text" name="number"/><br/>
<label>姓名</label>
<input type="text" name="name"/><br/>
<input type="button" value="添加一行" onclick="addRow();" /> <!--在添加按钮上添加点击事件 -->
</body>
</html>