var tr = document.getElementsByTagName('tr');
tr[0].onmouseover = function(){
tr[0].style.backgroundColor = '#ccc';
}
tr[1].onmouseover = function(){
tr[1].style.backgroundColor = '#ccc';
}
tr[2].onmouseover = function(){
tr[2].style.backgroundColor = '#ccc';
}
第一个是正确的,但当我使用for
循环时,如下面的代码段中所示,我得到“Uncaught TypeError: Cannot read property 'style' of undefined
”。
var tr = document.getElementsByTagName('tr');
for(var i=0;i<tr.length;i++){
tr[i].onmouseover = function(){
tr[i].style.backgroundColor = '#ccc';
}
}
答案 0 :(得分:1)
您需要从
更新 tr[i].onmouseover = function(){
tr[i].style.backgroundColor = '#ccc';
}
到
tr[i].onmouseover = function(event){
event.currentTarget.style.backgroundColor = '#ccc';
}
问题 - 当您尝试访问tr[i]
时事件处理程序值i
更新为3并因此发生错误