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';
}
}
最佳答案
您需要更新
tr[i].onmouseover = function(){
tr[i].style.backgroundColor = '#ccc';
}
至
tr[i].onmouseover = function(event){
event.currentTarget.style.backgroundColor = '#ccc';
}
问题 - 当您尝试访问事件处理程序中的 tr[i]
时,i
的值已更新为 3,因此发生了错误
关于javascript - 这两种说法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824609/