Sow nothing reap nothing

关于火狐(firefox)及其他浏览器下event获取的两种方法

已有2,397次关注

很多时候我们会用到event事件,大获取event的功能两种方法,火狐浏览器下不支持var e = e||window.event;
其他浏览器调用方法:

function a(e){ 
  e = e||window.event; 
  console.log(e); 
} 

浏览器如下调用:

<body onclick="a()"> 

火狐浏览器下需要使用以下方法:

function a(){ 
  e = arguments.callee.caller.arguments[0] || window.event; 
  console.log(e); 
}

火狐浏览器下如下调用:

<body onclick="a()">

这里要解释一下arguments.callee.caller.arguments[0], 简单例子如下:

function a(){ 
  b(); 
} 
function b(){ 
  alert(b === arguments.callee) 
  alert(b.caller === a) 
  alert(arguments.callee.caller === a) 
} 
a(); 

上面的这个例子将输出3个true,表明当a()调用时,函数b与函数a的关系。
arguments.callee指的就是当前的函数体。
arguments.callee.caller就是当前函数的上级函数 。
所以当执行onclick="a()"时arguments.callee就是a(),arguments.callee.caller就是function onclick。 onclick的第一个能数就是event,也就是arguments.callee.caller.arguments[0]这个。

已自动关闭评论