Event.preventDefault () and several events

Before starting to write huge pieces of code that don't work, I thought I was asking this question.

event.preventDefault() overrides the default action for a non-default click event?

Theoretically, I should be able to attach several click event handlers in jQuery to a given target to perform various actions, such as Ajax messages and Google tracking.

Am I really wrong?

+5
source share
1 answer

event.preventDefault() overrides the default action for a non-default click event?

( click) ( W3C, jQuery ). , , submit , . , , ; stopPropagation (W3C docs, jQuery docs).

, , div, click, , div. preventDefault, ( ), DOM , div, . click. , , preventDefault.

. , preventDefault, stopPropagation , ... stopImmediatePropagation, jQuery , ( ).

, , , , false , jQuery, . preventDefault stopPropagation. , .

, HTML:

<div id='foo'><a href='http://stackoverflow.com'>Q&amp;A</a></div>

1:

// Here we're preventing the default but not stopping bubbling,
// and so the browser won't follow the link, but the div will
// see the event and the alert will fire.
$("#foo").click(function() {
    alert("foo clicked");
});
$("#foo a").click(function(event) {
    event.preventDefault();
});

2:

// Here we're stopping propagation and not preventing the default;
// the browser will follow the link and the div will not be given
// a chance to process the event (no alert, and more to the point,
// code in the div handler can't prevent the default)
$("#foo").click(function() {
    alert("foo clicked");
});
$("#foo a").click(function(event) {
    event.stopPropagation();
});

3 ( ):

// Here we're doing both, and so the browser doesn't follow the
// link and the div doesn't see the event (no alert).
$("#foo").click(function() {
    alert("foo clicked");
});
$("#foo a").click(function(event) {
    event.preventDefault();
    event.stopPropagation();
});

4:

// Shorter version of Example 3, exactly the same effect
$("#foo").click(function() {
    alert("foo clicked");
});
$("#foo a").click(function() {
    return false;
});
+24

All Articles