这两个陈述有什么区别?

时间:2016-01-16 07:27:03

标签: javascript onmouseover

     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'; 
          }            
        }

1 个答案:

答案 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并因此发生错误