Usually we get the event object generally written as follows:
Copy Code code as follows:
function GetEvent (event) {
Return Event | | Window.event//IE:window.event
}
If there are no arguments, it can be written (non ie: the event object is automatically passed to the corresponding event handler and the first argument):
Copy Code code as follows:
function GetEvent () {
return Arguments[0] | | Window.event//IE:window.event
}
Such a way of writing in addition to Firefox (Beta version: 3.0.12, the same as the same) browser on the run will not be a problem, but Firefox why the exception? Let's take a situation like this:
Copy Code code as follows:
<button id= "btn" onclick= "foo ()" > button </button>
<script>
function foo () {
var e = getEvent ();
Alert (e);}
</script>
Running results in Firefox is undefined, why?
In Firefox the call is actually like this, the first call to execute is:
Copy Code code as follows:
function onclick (event) {
Foo ();
}
The call is then executed by:
Copy Code code as follows:
function foo () {
var e = getEvent ();
Alert (e);
}
You will find that the Foo () in onclick= "foo ()" In Firefox cannot automatically pass in the event object parameters, and the default is passed to the system-generated onclick function, which we can pass through the getEvent.caller.caller.arguments [0] Gets the event object.
Therefore, our getEvent can be optimized (refer to the GetEvent method in the Event/event-debug.js in yui_2.7.0b):
Copy Code code as follows:
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)) {/Yiwen Fei Note: YUI source bug,ev.constructor may also be mouseevent, not necessarily an Event
Break
}
c = C.caller;
}
}
return EV;
}
One simple solution, of course, is to manually pass parameters to onclick= "foo ()":
Copy Code code as follows:
<button id= "btn" onclick= "foo (event)" > button </button>