Let me begin by saying I understand that the below code has a major issue. Specifically, the event
parameter is not passed into the function. What I don't understand is why in the below code Chrome, Opera, Safari, Firefox, and IE all treat the event
variable differently.
$('#eventBtn').on('click', function() {
console.log(event);
event.preventDefault();
});
In Chrome, Opera, and Safari the above code works. IE fails at the second line and Firefox fails immediately. For testing purposes I have created a slightly more embellished jsFiddle. The output of the above console.log(event)
in the various browsers:
Chrome Version 26.0.1410.64 m
MouseEvent {dataTransfer: null, toElement: button#superBtn, fromElement: null,
y: 20, x: 33…}
Opera Version 12.15
MouseEvent
Safari Version 6.0.2 (8536.26.17)
MouseEvent
IE Version 10.0.9200.16540
[object MSEventObj]
Firefox Version 20.0.1
ReferenceError: event is not defined
I was bit by this "feature" of Chrome, Opera, and Safari because it worked as intended not as coded creating unexpected behavior in other browsers. While IE also has a global event
variable, unlike the aforementioned browsers it does not assign that variable to the event that is currently firing. Firefox does not have a global event
variable and therefore fails as soon as event
is referenced.
Typically I use e
for representing event variables which as expected fails the same way in all browsers. Why do Chrome, Opera and Safari have a global event
variable which they assign this way? Is this behavior documented somewhere? Aside from don't use event
for variable naming any advice for dealing with this "feature"?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…