改变背景色的问题

来源:9-22 编程练习

NameZ

2016-03-10 13:34

var trs = document.getElementsByTagName("tr");
        changeColor(trs);     
             
        //循环在里面
     function changeColor(trs){
            for(var i=0;i<trs.length;i++){
                var tr = trs[i];
                tr.onmouseover = function(){
                    tr.style.backgroundColor = "#f2f2f2";
                }
                tr.onmouseout = function(){
                    tr.style.backgroundColor = "#fff";
                }
            }
            
     }
var trs = document.getElementsByTagName("tr");
        //循环在外面
        for(var i=0;i<trs.length;i++){
                changeColor(trs[i]);
            }           
     function changeColor(tr){
            tr.onmouseover = function(){
                tr.style.backgroundColor = "#f2f2f2";
            }
            tr.onmouseout = function(){
                tr.style.backgroundColor = "#fff";
            }           
     }

循环在里面始终只有最后一行会有改背景色的效果,而循环在外面3行都有。为什么?

写回答 关注

3回答

  • LeingK
    2016-03-10 14:21:38
    已采纳

    大哥,差点被你坑了一把,害的我都开始怀疑人生了。。。。

    你这是没有考虑到tr的作用域呀。。。。。。。。。。。。。。

      //循环在里面

         function changeColor(trs){

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

                    var tr = trs[i];

                    tr.onmouseover = function(){

                        tr.style.backgroundColor = "#f2f2f2";//当事件触发时for循环早就结束了,tr也变成了最后一个tr了

                                                                                    //肯定改变的是最后一个呀

                    }

                    tr.onmouseout = function(){

                        tr.style.backgroundColor = "#fff";

                    }

                }

         }

    ===============================

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

            //循环在外面

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

                    changeColor(trs[i]);

                }           

         function changeColor(tr){

                tr.onmouseover = function(){

                    tr.style.backgroundColor = "#f2f2f2";//事件触发了,for循环也结束了,但这里的tr只是个形参

                    //,不是for循环里面的那个tr,作用域只是这个匿名函数

                }

                tr.onmouseout = function(){

                    tr.style.backgroundColor = "#fff";

                }           

         }

    总结就是,前者的tr都是同一个,而后者的tr不是同一个,当全局变量跟局部变量重名时,局部变量会覆盖掉全局变量,关于这一点,可以看看这里全局变量和局部变量

    格拉墨

    这个应该是JS的闭包问题,所以tr.onmouseover = function(){ this.style.backgroundColor = "#f2f2f2"; }就正常了

    2016-04-14 21:28:08

    共 4 条回复 >

  • 慕斯7245332
    2022-09-06 10:32:18

    你可以这么写div{text-align:center;}

    scxveg

  • 格拉墨
    2016-04-14 21:10:40

    不对吧,循环在里面,tr改成this就正常了

JavaScript进阶篇

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

467403 学习 · 21877 问题

查看课程

相似问题