色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

講兩件事:1.this指針的用法小探. 2.ie的attachEvent和firefox的addEventListener在事件處理上的區(qū)別

第一件事情.
this 指鐘是JavaScript語言中的一個特殊指鐘,他在代碼運行時,指向調用this語句的當前對象.
如果是事件綁定函數,則指向被綁定的元素本身.
<script type="text/Javascript">
//by Go_Rush(阿舜) from  http://ashun.cnblogs.com/
alert(this===window)  //true  直
接調用的時候,指向window本身
var gorush={
    f:function(){
        alert(this===gorush)    //true
    }
}
gorush.f()   //指向 gorush對象
document.onclick=function(){   
    alert(this===document)  //true ,指向 document
}
/*
element.onclick=function(){
    alert(this===element)     //true
}
*/
</script>
特別要值得注意的是,當多個對象嵌套的時候, this 是指向最近調用它的那個對象的
obj1={
    obj2:{
        f:function(){
            alert(this===obj1.obj2)  //這里 this 并不是指向 obj1的哦。
        }
    }
}
obj1.obj2.f()
再舉一個非常容易出錯的例子,  點這里看相關鏈接
<script type="text/Javascript">
//by Go_Rush from http://ashun.cnblogs.com/
//以下gorush1中 this的用法是錯誤的,這個錯誤10個程序員6個犯
var gorush1={
    showMsg:function(){alert("hello,world")},
    doAjax:function(){
        new Ajax.Request("index.php",{onSuccess:function(){
            this.showMsg()
        }})
    }         
}
//gorush2中的才是對的
var gorush2={
    showMsg:function(){alert("hello,world")},
    doAjax:function(){
        var self=this;    //備份 gorush2對象 
        new Ajax.Request("index.php",{onSuccess:function(){
            self.showMsg()
        }})
    }         
}
</script>

第二件事情:
   閑話不多說,先上碟小菜.
<script type="text/Javascript">
var btn=null
window.onload=function(){
    btn=document.getElementById("btn")    
    if (window.attachEvent) btn.attachEvent("onclick",gorush);
    if (window.addEventListener) btn.addEventListener("click",gorush,false)
}
function gorush(){
    if (this===window) alert("this==window")   //ie6.0下,這句會執(zhí)行
    if (this===btn)        alert("this==btn")        //ff1.5下,  這句會執(zhí)行
}
</script>
<input type="button" value="click me" id="btn">
真不明白為什么 ie 會這樣搞,讓人很郁悶啊,為什么把 this 指向 window呢?
解決方法:
1. 事件綁定的時候不要用 attachEvent, 可憐的我,當時就是用的prototype.js的Event.Observe方法
這樣 element.onclick=function.....  這樣在兩個瀏覽器中 this 指鐘都指向 element
2. 在處理函數 gorush中 用 getEvent()方法統一獲取事件,然后在用 evt.srcElement || evt.target 獲取 element對象

JavaScript技術講兩件事:1.this指針的用法小探. 2.ie的attachEvent和firefox的addEventListener在事件處理上的區(qū)別,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 龙岩市| 兴文县| 彰武县| 崇信县| 武汉市| 杨浦区| 长白| 南澳县| 安阳市| 万安县| 靖宇县| 唐山市| 浦江县| 铜鼓县| 北川| 合水县| 兰溪市| 视频| 九龙坡区| 自治县| 阜新市| 华蓥市| 黔西县| 博爱县| 新源县| 舞阳县| 焉耆| 林西县| 南昌县| 通化市| 吉木萨尔县| 阿图什市| 新乡县| 榆林市| 桂林市| 渝北区| 衡山县| 呼玛县| 巴林右旗| 祥云县| 双柏县|