我自己只能想到这样的方法写出来,请大神们挑出错误并指导
var a = document.getElementsByTagName("tr");
for(var i = 0;i<=a.length;i++){
a[i].onmouseover = function(){
this.style.backgroundColor= "#f2f2f2";
}
a[i].onmouseout = function(){
this.style.backgroundColor = "#fff";
}
}
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function add(){
var b = document.getElementById("table");
var c = document.createElement("tr");
var d = document.createElement("td");
var e = document.createElement("td");
var f = document.createElement("td");
var g = document.createElement("a");
d.innerHTML = "xh003";
e.innerHTML = "张学友";
g.innerHTML = "删除";
g.setAttribute("href","javascript:;")
f.appendChild(g);
c.appendChild(f);
c.insertBefore(e,f);
c.insertBefore(d,e);
b.appendChild(c);
}
// 创建删除函数
function move(ev){
var b = document.getElementById("table");
var a = document.getElementsByTagName("a");
for(var i = 0;i<=a.length;i++){
b.removeChild(a[i])
}
}
现在的参考了一下,修改为这样了(但是新增的删除按钮不好使):
function add(ojg){
var b = document.getElementById("table").lastChild;
var c = document.createElement("tr");
var d = document.createElement("td");
var e = document.createElement("td");
var f = document.createElement("td");
var g = document.createElement("a");
d.innerHTML = "xh003";
e.innerHTML = "张学友";
g.innerHTML = "<a>删除</a>";
g.setAttribute("href","javascript:;")
g.onClick=function(){delLine(this);};
f.appendChild(g);
c.appendChild(f);
c.insertBefore(e,f);
c.insertBefore(d,e);
b.appendChild(c);
var aa = document.getElementsByTagName("tr");
for(var i = 0;i<=aa.length;i++){
aa[i].onmouseover = function(){
this.style.backgroundColor= "#f2f2f2";
}
aa[i].onmouseout = function(){
this.style.backgroundColor = "#fff";
}
}
}
// 创建删除函数
function delLine(ojg){
var del1=ojg.parentNode.parentNode.parentNode;
var del2=ojg.parentNode.parentNode;
del1.removeChild(del2);
}
</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 = "delLine(this)" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" onclick = "delLine(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</table>
<input type="button" value="添加一行" onclick = "add(this)"/> <!--在添加按钮上添加点击事件 -->