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

来源:9-22 编程练习

一点儿也不

2015-11-16 21:26

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

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

写回答 关注

3回答

  • 李晓健
    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-18 10:15:58

    共 3 条回复 >

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

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

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

    一点儿也不 回复vivian...

    好像是这么个理。它复制的有点类似于文本,而不是根据实际来改变对象属性。

    2015-11-29 16:06:12

    共 3 条回复 >

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

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

JavaScript进阶篇

本课程从如何插入JS代码开始,带您进入网页动态交互世界

469388 学习 · 22585 问题

查看课程

相似问题