Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - Unexpected access to "event" variable across browsers?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IE has always provided a global event variable, unlike what the W3C standards dictate. The other browsers are doing the same in order to provide backward-compatibility with websites developed with old IE versions in mind.

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.

I believe it does.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...