Usually, we usually write the event object as follows:
function getEvent(event) {
return event || window.event // IE:window.event
}
If there are no parameters, it can also be written as (non-IE: the event object will be automatically passed to the corresponding event processing function and is the first parameter):
function getEvent() {
return arguments[0] || window.event // IE:window.event
}
This way of writing will have no problem running on browsers other than Firefox (test version: 3.0.12, the same below), but why is Firefox an exception? Let's take a situation like this:
<button id="btn" onclick="foo()">Button</button>
<script>
function foo(){
var e = getEvent();
alert(e);}
</script>
The running result is undefined in Firefox, why?
The call in Firefox is actually like this. The first call to execute is:
function onclick(event) {
foo();
}
Then the call is executed:
function foo(){
var e = getEvent();
alert(e);
}
You will find that foo() in onclick="foo()" under Firefox cannot automatically pass in the event object parameters, but is passed to the onclick function generated by the system by default. In this example, we can pass getEvent.caller.caller.arguments[ 0] Get the event object.
Therefore, our getEvent can be optimized into (refer to the getEvent method in event/event-debug.js in yui_2.7.0b):
function getEvent(event) {
var ev = event || window.event;
if (!ev) {
var c = this.getEvent.caller;
while (c) {
ev = c.arguments[0];
if (ev && (Event == ev.constructor || MouseEvent == ev.constructor)) { /Yi Fei’s note: YUI source code BUG, ev.constructor may also be MouseEvent, not necessarily Event
break;
}
c = c.caller;
}
}
return ev;
}
Of course, there is a very simple solution, which is to manually pass the parameters to onclick="foo()":
<button id="btn" onclick="foo(event)">Button</button>