一个事件切换器上的问题

不太描述得清楚,就直接上代码吧。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    .red{
        width:100px;
        height: 100px;
        background: red;
    }    
    .blue{
        width: 100px;
        height: 100px;
        background: blue;
    }
    </style>
    <script>
        window.onload=function(){
            var box=document.getElementById('box');
            box.onclick=toBlue;
            
           // box.onclick=function(){  为什么通过这种方式没法执行函数。
             //   toBlue(); 
           // }
        }
        function toRed(){
            this.className='red';
            this.onclick=toBlue;

        }
        function toBlue(){
            this.className='blue';
            this.onclick=toRed;
        }
    </script>
</head>
<body>
    <div id='box' class='red'>测试div</div>
</body>
</html>
阅读 1.9k
2 个回答

因为this指向的是函数的执行上下文,像你这样直接调用 toBlue() 那么,this则指向了window对象

this指向的问题,像这样的情况,打个断点跟踪一下就知道了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题