function on(tr1){
tr1.onmouseover=function(){
tr1.style.backgroundColor="#f2f2f2";
}
tr1.onmouseout=function(){
tr1.style.backgroundColor="#fff";
}
}
for(var i=0;i<rows.length;i++){
on(rows[i]);
}
把上述代码改写成图片中的代码就只能应用到第三行,chrome中检查无语法错误;如果把变量tr1全部改成rows[i]则失效。chrome中检查出row[i]是undefined
<!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 rows=document.getElementsByTagName("tr");
for(var i=0;i<rows.length;i++){
on(rows[i]);
}
}
function on(tr1)//把这个函数从 window.onload里拿出来,让下面添加行的函数也能用
tr1.onmouseover=function(){
tr1.style.backgroundColor="#f2f2f2";
}
tr1.onmouseout=function(){
tr1.style.backgroundColor="#fff";
}
}
function addRow(){
var xh=prompt("请输入学号:","xh0");
var xm=prompt("请输入姓名");
var tr=document.createElement("tr");
var td0=document.createElement("td");
var td1=document.createElement("td");
var td2=document.createElement("td");
td0.innerHTML=xh;
td1.innerHTML=xm;
td2.innerHTML="<a href='javascript:;' onclick='deleteRow(this)'>删除</a>";
var tbody=document.getElementById("table").lastChild;
while(tbody.nodeType!=1){
var i=1;
tbody=document.getElementById("table").childNodes[(document.getElementById("table").childNodes.length-1-i)];
i++;
}
tbody.appendChild(tr);
tr.appendChild(td0);
tr.appendChild(td1);
tr.appendChild(td2);
on(tr);//动态添加的tr也要给绑上2个鼠标事件
}
function deleteRow(obj){
var tb=obj.parentNode.parentNode.parentNode;
var tr=obj.parentNode.parentNode;
tb.removeChild(tr);
}
</script>
</head>
<body>
<table border="1" width="50%" id="table">
<thead><tr>
<th>学号</th>
<th>姓名</th>
<th>操作</th>
</tr></thead>
<tbody>
<tr>
<td>xh001</td>
<td>王小明</td>
<td><a href="javascript:; " onclick="deleteRow(this)" >删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
<tr>
<td>xh002</td>
<td>刘小芳</td>
<td><a href="javascript:;" onclick="deleteRow(this)">删除</a></td> <!--在删除按钮上添加点击事件 -->
</tr>
</tbody>
</table>
<input type="button" value="添加一行" onclick="addRow()" /> <!--在添加按钮上添加点击事件 -->
</body>
</html>
定义rows了吗?
var trList = document.getElementsByTagName('li'); for(var i=0; i< trList.length; i++){ trList[i].onmouseover = function(){ this.style.backgroundColor = '#f2f2f2'; }; trList[i].onmouseout = function(){ this.style.backgroundColor = '#fff'; }; };