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.
- By default, the child's click event should happen first. – Rick Hitchcock Commented Jul 8, 2015 at 22:59
1 Answer
Reset to default 5Are 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
版权声明:本文标题:Set order of mouse click events JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744743012a2622721.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论