慕尼黑3533373
2020-02-18 23:47
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript">
function on(node){
node.style.backgroundColor = "#f2f2f2";
}
function out(node){
node.style.backgroundColor = "#fff";
}
window.onload = function(){
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
var row = document.getElementsByTagName("tr");
for (var i = 0; i < row.length; i++){
row[i].onmouseover = function (){
this.style.backgroundColor = "#f2f2f2";
}
row[i].onmouseout = function (){
this.style.backgroundColor = "#fff";
}
}
}
// 创建删除函数
function dele(node){
var tr = node.parentNode.parentNode;
tr.parentNode.removeChild(tr);
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function add(){
var table = document.getElementsByTagName("tbody")[0];
var r = document.createElement("tr");
r.setAttribute("onmouseover","on(this)");
r.setAttribute("onmouseout","out(this)");
table.appendChild(r);
for (var i = 3; i > 0; i--){
var h = document.createElement("td");
if(i == 3){
var num = document.getElementsByTagName("tr").length-1;
if (num < 10){
h.innerHTML = "xh00"+num;
}
else if(num < 100){
h.innerHTML = "xh0"+num;
}
else h.innerHTML = "xh"+num;
}
if (i == 2){
h.innerHTML = prompt("请输入姓名","如:张三");
}
if (i == 1){
var a = document.createElement("a");
a.href = "javascript:";
a.innerHTML = "删除";
a.setAttribute("onclick","dele(this)");
h.appendChild(a);
}
r.appendChild(h);
}
}
</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:" onclick=dele(this)>删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:"onclick=dele(this) >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input type="button" value="添加一行" onclick=add() /> <!--在添加按钮上添加点击事件 -->
</body>
</html>
这样也可以:
row[i].onmouseover=function(){on(this)};
设置鼠标事件的时候可以改成这样:
row[i].setAttribute("onmouseover",'javascript:on(this)');
row[i].setAttribute("onmouseout",'javascript:out(this)');
JavaScript进阶篇
468061 学习 · 21891 问题
相似问题