问答详情
源自:9-22 编程练习

求指点迷津,我的onload函数哪里写错了,得不到想要的结果 !!

求大神指点一下迷津,我写的错在哪里? 

window.onload = function(){ 
         var tr = document.getElementsByTagName("tr");
         for ( var i=0;i<tr.length;i++ ){
                //循环遍历改变属性及方法;
                 tr[i].onmouseover = function(){
                          tr[i].style.backgroundColor = "#f2f2f2";
                };
                tr[i].onmouseout = function(){
                          tr[i].style.backgroundColor = "#fff";
                }; 
        } 
}

提问者:一点儿也不 2015-11-16 21:26

个回答

  • 李晓健
    2015-11-17 12:50:17
    已采纳

    window.onload = function(){
            var tr = document.getElementsByTagName("tr");        
            for ( var i=0;i<tr.length;i++ ){
                var ctr = tr[i];
                (function(ctr){
                    ctr.onmouseover = function(){
                        ctr.style.backgroundColor = "#f2f2f2";
                    };
                    ctr.onmouseout = function(){
                        ctr.style.backgroundColor = "#fff";
                    };
                }(ctr))
            }
        }
    window.onload = function(){
            var tr = document.getElementsByTagName("tr");
            for ( var i=0;i<tr.length;i++ ){
                var ctr = tr[i];
                //循环遍历改变属性及方法;
                tr[i].onmouseover = function(){
                    this.style.backgroundColor = "#f2f2f2";
                };
                tr[i].onmouseout = function(){
                    this.style.backgroundColor = "#fff";
               };
            }
        }

    以上两种方法都可以

  • 荼酒
    2015-11-17 10:22:05

    this表示当前对象啊,你每个tr都绑定了mouseover事件,鼠标经过当前对象后触发事件~改变背景颜色,

    如果是tr[i].style.backgroundColor = "#f2f2f2"; 那么这里的i无法指向当前经过了哪个对象。

  • 一点儿也不
    2015-11-16 21:30:42

    将onmouseover与out函数里面的tr[i]换成this却可以成功运行,求解释???