admin管理员组

文章数量:1391955

I have two elements - a parent and a child. Both have on click event handlers. If I click on the child element then both event handlers run - parent's first then child's (at least on Chrome). I don't know how the browser determines which order to run the events in, but is there a way to specifically set this order so that the child's click event happens before the parent's click event?

I have found a lot of questions and answers regarding the order of different events (mousedown, click, etc.), but can't find anything regarding the order of the same event on different elements.

I have two elements - a parent and a child. Both have on click event handlers. If I click on the child element then both event handlers run - parent's first then child's (at least on Chrome). I don't know how the browser determines which order to run the events in, but is there a way to specifically set this order so that the child's click event happens before the parent's click event?

I have found a lot of questions and answers regarding the order of different events (mousedown, click, etc.), but can't find anything regarding the order of the same event on different elements.

Share Improve this question edited Mar 12, 2022 at 12:32 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 8, 2015 at 22:35 MrMadsenMrMadsen 3,0123 gold badges23 silver badges31 bronze badges 1
  • By default, the child's click event should happen first. – Rick Hitchcock Commented Jul 8, 2015 at 22:59
Add a ment  | 

1 Answer 1

Reset to default 5

Are you sure the parent's runs first? Events bubble from the innermost element to the outermost element (your child click handler should trigger before your parent). From http://api.jquery./on/:

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble

That said, if you always want the behavior of the parent element to execute first you could do the following:

function runFirst(){
    alert("I should always run first");   
}

function runSecond(){
    alert("I should always run second");
}

$('body').on('click', '.parent', function(){

    runFirst();

}).on('click', '.child', function(event){

    runFirst();
    runSecond();

    event.stopPropagation();
});

Here's a fiddle demonstrating the behavior: https://jsfiddle/8fxout3d/1/

本文标签: Set order of mouse click events JavaScriptStack Overflow