给新增行加上事件函数即可
那是因为,变色效果写在了onload事件里,而该事件是在页面加载完成时触发的,此时trs.length是2,也就是说之后及时再添加新行,也只有前两列有颜色效果,若想要新加的行也有变色效果,需要在新添加一行时,给改行加上变色效果,即在add()函数的最后一行添加了change()函数代码如下:
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<script type="text/javascript">
window.onload = function(){
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
var tr=document.getElementsByTagName("tr");
for(var i=0; i<tr.length;i++){
tr[i].onmouseover=function(){
this.style.backgroundColor="#f2f2f2";
}
tr[i].onmouseout=function(){
this.style.backgroundColor="#fff";
}
}
}
function change(){
var tr=document.getElementsByTagName("tr");
tr[tr.length-1].onmouseover=function(){
this.style.backgroundColor="#f2f2f2";
}
tr[tr.length-1].onmouseout=function(){
this.style.backgroundColor="#fff";
}
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
function add(){
var table=document.getElementById('table');
var tr=document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = "<input type='text'/>";
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = "<input type='text'/>";
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = "<a href='javascript:;' onclick='del(this)'>删除</a>";
tr.appendChild(td);
table.appendChild(tr);
change();
}
// 创建删除函数
function del(obj){
var tr = obj.parentNode.parentNode;
tr.parentNode.removeChild(tr);
}
</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="del(this)">删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> <tr> <td>xh002</td> <td>刘小芳</td> <td><a href="javascript:;" onclick="del(this)" >删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> </table> <input type="button" value="添加一行" onclick="add()"/> <!--在添加按钮上添加点击事件 --> </body> </html>