夺命雷公狗jquery---25事件绑定中的this指向

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            div#result{
                background-color:blue;
                width:500px;
                height:500px;
            }
        </style>
        <script src="js/jquery.js"></script>
        <script>
            $(function(){
                $('#result').bind('click',function(){
                    //alert(this);
                    //alert(this.id);
                    //this.style.backgroundColor = 'red';
                    //其内部的this指向当前要操作的DOM对象
                    //所以可以使用this.backgroundColor或者this.id  DOM的属性和方法
                    //this.css('background-color','red'); 这样是不可以的,因为当前的this指向的DOM对象
                    $(this).css('background-color','red');
                })
            });
        </script>
    </head>
    <body>
        <div id="result"></div>
    </body>
</html>

在原生JavaScript代码中,事件监听程序中的this比较特殊,具有兼容性问题:

当使用IE浏览器进行事件绑定时,其内部的this指向window对象

当使用W3C浏览器时,其内部this指向当前DOM对象

在jQuery中,jQuery调整了事件绑定的兼容性问题,统一更改其内部的this指向为当前要操作的DOM对象。

通过运行代码调试可知,在jQuery中,其内部的this指向了当前要操作的DOM对象,说明:如果要使用jQuery的属性和方法,必须通过$符号进行封装.

原文地址:https://www.cnblogs.com/leigood/p/4914222.html