设置背景颜色的时候为什么要用this?

来源:9-22 编程练习

Elvis_Nam

2016-03-05 14:53

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

在上面这代码中,鼠标经过而触发改动背景颜色的函数中,为什么要用“this.style.backgroundColor="#fff";”  我一开始是设想使用“oTr[i].style.backgroundColor="#fff";",结果失败了。

求帮忙告知下失败的原因是什么,谢谢!!!

写回答 关注

1回答

  • 长颈鹿在附近
    2016-03-05 19:53:22

    http://img.mukewang.com/56dac83d0001eb6410694600.jpg

    找到一篇博客讲这个问题,貌似是函数中必须用this来调用属性和方法,我也试了用trs[i],达不到效果

JavaScript进阶篇

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

469231 学习 · 22584 问题

查看课程

相似问题