为啥1行2不行呢

来源:9-22 编程练习

山岳之王

2016-02-25 10:29

1:

     /* window.onload = function(){

        var hang=document.getElementsByTagName('tr');

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

           bdc(hang[i]);

            }

        }

     function bdc(can){

         can.onmouseover=function(){

             can.style.backgroundColor="#f2f2f2";

         }

         can.onmouseout=function(){

             can.style.backgroundColor="#fff";

         }

     }*/

2:     

    window.onload = function(){

        var hang=document.getElementsByTagName('tr');

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

            hang[i].onmouseover=function(){

                hang[i].style.backgroundColor="#f2f2f2";

            }

            hang[i].onmouseout=function(){

                hang[i].style.backgroundColor="#fff";

            }

        }

    }


写回答 关注

2回答

  • 白瑞爷
    2016-02-25 16:12:41
    已采纳

    2改成

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

                hang[i].onmouseover=function(){

                    this.style.backgroundColor="#f2f2f2";

                }

                hang[i].onmouseout=function(){

                    this.style.backgroundColor="#fff";

                }

    }

    就好了呢~

    因为在你嵌套的函数里面并不知道hang[i]是谁啊~

    作用域的问题

    白瑞爷 回复山岳之王

    客气了~大家共同交流

    2016-02-29 14:00:07

    共 2 条回复 >

  • 爱学习要努力
    2016-02-25 18:08:51

    如楼上所言改成this试试。1的函数里带参数

JavaScript进阶篇

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

467395 学习 · 21877 问题

查看课程

相似问题