两者有什么区别?求大神指教!

来源:9-22 编程练习

DOMOHAHA

2016-02-04 18:38

   为什么这样可以, 

  window.onload = function(){

          var tr=document.getElementsByTagName("tr");

          for(var i= 0;i<tr.length;i++)

          {

              bgcChange(tr[i]);

          }

     // 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。

      }         

function bgcChange(obj)

     {

        obj.onmouseover=function(){

            obj.style.backgroundColor="#f2f2f2";

        }

        obj.onmouseout=function(){

            obj.style.backgroundColor="#fff";

        }

}

这样却不行?

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

          }

     }


写回答 关注

2回答

  • 前端狩猎者
    2016-02-10 12:06:33

    将  tr[i].style.backgroundColor="#f2f2f2"; 改为 this.style.backgroundColor="#f2f2f2";

  • MochaCat
    2016-02-06 15:41:47

    window.onload = function(){
       var tr=document.getElementsByTagName("tr");
       for(var i= 0;i<tr.length;i++)
       {
           tr[i].onmouseover=function(){
               this.style.backgroundColor="#f2f2f2";        }
           tr[i].onmouseout=function(i){
               this.style.backgroundColor="#fff";        }
       }
    }

    这样就行;

    首先

    tr[i].onmouseover=function(){

                tr[i].style.backgroundColor="#f2f2f2";        }

    这里 function里面的tr[i]因为变量作用域的关系是不存在的,把它换为当前对象this就解决了。

JavaScript进阶篇

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

467396 学习 · 21877 问题

查看课程

相似问题