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
268 views
in Technique[技术] by (71.8m points)

jQuery .on(); vs JavaScript .addEventListener();

Can someone explain me why is there a difference in the order in which the event handlers are being executed depending on how they have been attached? In the example below I'm using the .on() and .addEventListener() methods to handle a specific event on different DOM elements.

jsfiddle: http://jsfiddle.net/etsS2/

I thought that in this particular example the order in which the event handlers are going to be executed will depend on the event-bubbling - so starting from the original event target and moving up to the document element.

document.getElementById('outer').addEventListener('mouseup', function (event) {
//$('#outer').on('mouseup', function (event) {
    alert('This alert should not show up!');
}, false);

If I uncomment the on(); version everything works as expected - is there a difference in how jQuery handles events contrary to plain JavaScript?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When you use .on() at the document level, you're waiting for the event to bubble all the way up to that point. The event handler for any intermediate container will already have been called.

Event "bubbling" is the process by which the browser looks for event handlers registered with parents of the element that was the actual original recipient of the event. It works upwards in the DOM tree. The document level is the last level checked. Thus, your handler registered with .on() won't run until that level is reached. In the meantime, the other event handler at the "outer" level is reached first and it is executed by the browser.

Thus, that return false; in the handler registered with .on() is pretty much useless, as would be a call to event.stopPropagation(). Beyond that, mixing native event handler registration with the work that a library like jQuery will do is probably a really bad idea unless you seriously know what you're doing.

There was a question asked almost exactly like this one just a little while ago today.


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

...