<!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 list = document.getElementsByTagName("tr")
for(var i = 0; i < list.length; i++){
list[i].onmouseover = function(){
this.style.backgroundColor = "red"
}
list[i].onmouseout = function(){
this.style.backgroundColor = "white"
}
}
}
// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;
// 创建删除函数
</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>
</table>
<input type="button" value="添加一行" /> <!--在添加按钮上添加点击事件 -->
</body>
</html>用list[i] 和用this本质是一样的,你去运行一下就知道了。list[i]并不是整个表格,就是那一列。
应为this获取的是当前对象。
var tbody = document.getElementById('table').lastChild;这里获取的是整个表格
如果你把this.style.backgroundColor ="#f2f2f2";改成这样tbody.style.backgroundColor ="#f2f2f2";那整个表格就起作用了。
function Highlight(){
var tbody = document.getElementById('table').lastChild;
trs = tbody.getElementsByTagName('tr'); //获取表格的行
for(var i =1;i<trs.length;i++){ //然后遍历每个行存放在数组trs[i]中
trs[i].onmouseover = function(){ //此时这里的trs[i]就相当于对象了(因为数组本身是对象)
this.style.backgroundColor ="#f2f2f2";//this是调用当前对象的(当鼠标放到哪一行,当前这一行就会触发事件了)
}
trs[i].onmouseout = function(){
this.style.backgroundColor ="#fff";
}
}
}
我水平本身也有限,希望能帮到你