这两种说法有什么区别?
What is difference between these two statements?
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,因此发生了错误
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,因此发生了错误