Home > Web Front-end > JS Tutorial > JavaScript gets the attention points of the event object_javascript skills

JavaScript gets the attention points of the event object_javascript skills

WBOY
Release: 2016-05-16 18:49:10
Original
1340 people have browsed it

Usually we usually write the event object as follows:

Copy the code The code is 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 Automatically passed to the corresponding event processing function and is the first parameter):
Copy code The code is as follows:

function getEvent() {
return arguments[0] || window.event // IE:window.event
}

This writing method works well except for Firefox ( Test version: 3.0.12, the same below) There will be no problem running on other browsers, but why is Firefox an exception? Let us have a situation like this:
Copy code The code is as follows:


<script> <br>function foo(){ <br>var e = getEvent(); <br>alert(e) ;} <br></script>

The running result is undefined in Firefox, why?
The actual call in Firefox is like this. The first call is:
Copy the code The code is as follows:

function onclick(event) {
foo();
}

Then the call is executed:
Copy code The code is as follows:

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. For example, we can get the event object through getEvent.caller.caller.arguments[0].
Therefore, our getEvent can be optimized into (refer to the getEvent method in event/event-debug.js in yui_2.7.0b):
Copy code The code is 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)) { /Yi Fei 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()":
Copy code The code is as follows:



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template