解决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]来获取了..

 

posted on 2015-12-20 20:14  蓝萝卜blu  阅读(3192)  评论(0编辑  收藏  举报

导航