Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Why is 'event' variable available even when not passed as a parameter?

I wonder why does the following code work in some browsers? I.e. even when there's no parameter to a click() function however event variable exists and dosomething method is called on the event trigger object?

$(<selector>).click(function () {
  $(event.target).<dosomething>
});
Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Why is 'event' variable available even when not passed as a parameter?

It isn't, reliably. That code will fail on Firefox, for instance. It wasn't and used to fail on Firefox. Microsoft used a global event variable. DOM2 defined it as an argument to the handler. Chrome decided to throw MS-specific code a bone and do both. For a long time, Firefox did not. But the global was standardized as a legacy API for compatibility reasons (spec | MDN) and Firefox added it in v63, briefly put it behind a flag the user had to enable, and since v66 ships with it unflagged.

Even on the browsers where that code works, note that event will be a raw event object, not the jQuery-enhanced one. That means that, for instance, on IE8 you can't call event.preventDefault because IE8 doesn't supply that function. jQuery would if you accepted the argument, because jQuery provides an event object with standardized features even on browsers that are missing those features.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...