js中this及碰触浮现div实例

来源:互联网 发布:win2008端口转发 编辑:程序博客网 时间:2024/06/07 17:34

         js中this的用法

 this:指的是调用当前方法 (函数)的那个对象,切记,一定要是当前的那一个!
 this使用时的几种情况:
1)   alert(this); this指向的是window  
alret(this);实际是缩写,全写为window.alert(this); 所以此时alert的当前其实就是windou
2) function fn(){
alert(this);
}
fn(); this指向的是window 
记忆时可以偷懒的记忆只要是函数的直接调用,都是window
3)   var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
alert(this); this指向的是input
fn(); this指向的是window,此时的fn()不是当前的,所以得到的是window,而不是input。
}
4)如果在需要使用this时,发现this不是直接的,不能指向你想要的变量,可以先定义一个变量为空,把this存在里 面,在后面的代码中进行调用
this使用的实例:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js的this属性的运用</title>
        <style>
             h2{ height:30px; width:300px; border:2px solid pink; font-size:20px; text-align:center; line-height:30px; margin:40px auto;}
             li{ height:150px; width:100px; background:pink; border:2px solid #333; margin-top:30px; margin-left:250px; float:left; list-style:none;}
             div{ height:150px; width:200px; background:yellow; border:2px solid green; margin-top:100px; display:none;}
        </style>
        <script>
              window.onload = function(){
                var oUl = document.getElementById('list');
                var aLi = document.getElementsByTagName('li');
                var that = null;
                for(var i=0;i<aLi.length;i++){
                    aLi[i].onmousemove = function(){
                        that = this;
                        fn();
                    }
                    function fn(){
                        that.getElementsByTagName('div')[0].style.display = 'block';
                    }
                    aLi[i].onmouseout = function(){
                        this.getElementsByTagName('div')[0].style.display = 'none';
                    }
                }
              }
        </script>
    </head>
    <body>
        <h2>this属性应用实例</h2>
        <ul id="list">
            <li>
                <div></div>
            </li>
            <li>
                <div></div>
            </li>
            <li>
                <div></div>
            </li>
        </ul>
    </body>
</html>
这个例子在使用this的属性时,便通过了两种方法进行使用,一种是直接使用(用蓝色进行标记),另一种便是先把this存放到一个变量中,在后面的代码中进行调用。存this的变量为that(用红色进行标记)。



原创粉丝点击