JavaScript中同一事件绑定不同元素时的触发顺序判定规则咨询
Great question! Let's break down exactly what's happening here, using JavaScript's event propagation system as our guide.
The 3 Phases of Event Propagation
Every time an event (like a click) happens in the browser, it travels through three distinct phases:
- Capture Phase: The event starts at the top of the DOM tree (think
documentorwindow) and works its way down to the target element that was actually clicked. - Target Phase: The event reaches the exact element that triggered it (your
#someButtonin this case). - Bubble Phase: The event travels back up from the target element to the top of the DOM tree again.
jQuery's Default Behavior
When you use jQuery's .click() method (or its shorthand for .on('click', ...)), it automatically binds your event handler to the bubble phase of propagation. That's the key detail explaining your test results.
Why the Button Always Fires First
When you click #someButton:
- First, the event completes the capture phase (but since your handlers are bound to the bubble phase, nothing happens here yet).
- Next, the target phase kicks in: the button's click handler runs immediately, because it's the direct target of the click.
- Finally, the event starts bubbling up the DOM. It moves from the button to its parent elements, then to
body,html, and finally reachesdocument—where your second handler runs.
This is why the order you write the two handlers in your code doesn't matter: the bubble phase always moves from the innermost target element outward. The button is closer to the "source" of the click, so its handler runs first every time.
What If You Want the Document Handler to Run First?
If you ever need to reverse this order, you can bind the document handler to the capture phase instead. In jQuery, you can do this by passing true as the third argument to .on():
$(document).on('click', function(e) { // This will run BEFORE the button's handler }, true); $('#someButton').click(function(e) { // This runs second });
Now, during the capture phase, the document's handler fires first as the event travels down to the button, then the button's handler runs in the target phase.
内容的提问来源于stack exchange,提问作者Darkisa

