解決webkit瀏覽器中js方法中使用window.event提示未定義的問題


這實際上是一個瀏覽器兼容性問題,根源百度中一大堆,簡要說就是ie中event對象是全局變量,所以哪里都能使用到,但是webkit內核的瀏覽器中卻不存在這個全局變量event,而是以一個隱式的局部變量的形式傳入(后文會詳說).

function myfunc(param){
    alert(window.event);
}    

//ie中
<input type="button" onclick="myfunc('testie')" >    //一切正常

//webkit瀏覽器,如chrome,firefox之類的
<input type="button" onclick="myfunc('testwebkit')" >   //會提示undefined

然后這里解釋一下webkit內核的瀏覽器是如何隱式傳入的event對象.

還是上面那個例子,在webkit瀏覽器中,onclick="myfunc('testwebkit')" 這句實際上相當於這樣的:

onclick(event){
   myfunc('testwebkit');
}

換句話說onclick方法的0號參數實際上就是那個隱式傳進來的event對象.

然后我們再來看一下js方法中的一種調用:arguments.callee.caller,其中arguments為方法的參數集合,callee為當前參數所在的方法,caller就為調用此方法的方法(或者說調用者).

然后就有如下的對應關系:

function myfunc(param){
    alert(arguments.callee);   //myfunc()
    alert(arguments.callee.caller);  //onclick()
    alert(arguments.callee.caller.arguments[0]);  //event
}    

//webkit瀏覽器,如chrome,firefox之類的
<input type="button" onclick="myfunc('testwebkit')" >   

這里特別說一句,arguments.callee.caller是可以繼續往上追尋調用者的,比如arguments.callee.caller.arguments.callee.caller就是又向上追尋了一級.為何會特別說這個,因為有些時候會遇到自定義標簽之類的情況,這種情況中如果有封裝和js相關的方法,可能會存在如下這種情況:

onclick(event){
  tagCommand(){     //某些情況下的多層嵌套
      myfunc('testwebkit');
  }
}

此時如果還想在myfunc方法中獲取到event對象,就需要連往上追尋2級,使用arguments.callee.caller.arguments.callee.caller.arguments[0]來獲取了..

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM