首页 > 一个事件切换器上的问题

一个事件切换器上的问题

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

<!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>

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


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

【热门文章】
【热门文章】