JavaScript gets event Object

Source: Internet
Author: User
Tags object constructor return window
Usually we get the event object generally written 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):

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:

button

Running results in Firefox is undefined, why?

In Firefox the call is actually like this, the first call to execute is:

function onclick (event) {
Foo ();
}

The call is then executed by:

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):

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 Mouseeven T, not necessarily an Event
Break
}
c = C.caller;
}
}
return EV;
}

One simple solution, of course, is to manually pass parameters to onclick= "foo ()":

button



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.