为了账号安全,请及时绑定邮箱和手机立即绑定

改变背景色的问题

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 回答

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

你这是没有考虑到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不是同一个,当全局变量跟局部变量重名时,局部变量会覆盖掉全局变量,关于这一点,可以看看这里全局变量和局部变量

0 回复 有任何疑惑可以回复我~
#1

NameZ 提问者

感谢!我也不想坑你的呀!
2016-03-10 回复 有任何疑惑可以回复我~
#2

格拉墨

循环在里面的时候, var tr = trs[i]; tr.onmouseover = function(){ tr.style.backgroundColor = "#f2f2f2"; },这里面=号前后两个tr不相等,后面tr一直等于变量tr的最后一个值,即trs[2]。
2016-04-14 回复 有任何疑惑可以回复我~
#3

格拉墨 回复 格拉墨

所以循环在里面的时候,你鼠标不管移到哪行,都是最后一行触发
2016-04-14 回复 有任何疑惑可以回复我~
#4

格拉墨

这个应该是JS的闭包问题,所以tr.onmouseover = function(){ this.style.backgroundColor = "#f2f2f2"; }就正常了
2016-04-14 回复 有任何疑惑可以回复我~
查看1条回复

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

scxveg

0 回复 有任何疑惑可以回复我~

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

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

改变背景色的问题

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信