<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<!--<style type="text/css">
table{ background-color: #fff; }
tr:hover{background-color: #f2f2f2;}
</style>-->
<!--这里用CSS可以实现,以后开发中尽量用方便的,但是这个练习在练习的是js.所以用js来实现-->
<script type="text/javascript">
window.onload = function(){
var str_tr=document.getElementsByTagName('tr');
for(var i=0;i<str_tr.length;i++){
str_tr[i].setAttribute('onmouseover',document.all ? eval(function(){this.style.background="#f2f2f2"}) : 'javascript:this.style.background="#f2f2f2"');
str_tr[i].setAttribute('onmouseout',document.all?eval(function(){this.style.background="#fff"}):'javascript:this.style.background="#fff"');
}
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function add() {
var tbodyNode = document.getElementsByTagName("tbody")[0];
var trNode = document.createElement("tr");
var tdNode1 = document.createElement("td");
var tdNode2 = document.createElement("td");
var tdNode3 = document.createElement("td");
tdNode1.innerHTML="";
tdNode2.innerHTML="";
tdNode3.innerHTML="<a href='#' onclick='deleteR(this)'>删除</a>";
trNode.appendChild(tdNode1);
trNode.appendChild(tdNode2);
trNode.appendChild(tdNode3);
tbodyNode.appendChild(trNode);
var str_tr=document.getElementsByTagName('tr');
for(var i=0;i<str_tr.length;i++){
str_tr[i].setAttribute('onmouseover',document.all ? eval(function(){this.style.background="#f2f2f2"}) : 'javascript:this.style.background="#f2f2f2"');
str_tr[i].setAttribute('onmouseout',document.all?eval(function(){this.style.background="#fff"}):'javascript:this.style.background="#fff"');
}
}
// 创建删除函数
function deleteR(node) {
var tbody = node.parentNode.parentNode.parentNode;
tbody.removeChild(node.parentNode.parentNode);
}
</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="#" onclick="deleteR(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="#" onclick="deleteR(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input type="button" value="添加一行" onclick="add()"/> <!--在添加按钮上添加点击事件 -->
</body>
</html>
慢慢凑出来的,留着以后看看