@Libra's answer is very good, there just happen to be some people like me who understand better the interaction of the code with the machine.
因此,下面的脚本应该解释事件传播。
基于 描述模式我试图做的是:
下面的事件流向下和向上以下层次结构:
For the sake of simplicity we'll start at the body down to the span element registering handlers for the capturing phase, and back up to the body element registering handlers for the bubbling phase.
因此,结果将是事件从开始到结束所采取的方向的一个节点一个节点。
Please click "Show console " on the right panel of the snippet to access the logs
function handler(e){
/* logs messages of each phase of the event flow associated with
the actual node where the flow was passing by */
if ( e.eventPhase == Event.CAPTURING_PHASE ){
console.log ("capturing phase :\n actual node : "+this.nodeName);
}
if ( e.eventPhase == Event.AT_TARGET){
console.log( "at target phase :\n actual node : "+this.nodeName);
}
if ( e.eventPhase == Event.BUBBLING_PHASE){
console.log ("bubbling phase :\n actual node : "+this.nodeName );
}
}
/* The following array contains the elements between the target (span and you can
click also on the paragraph) and its ancestors up to the BODY element, it can still
go up to the "document" then the "window" element, for the sake of simplicity it is
chosen to stop here at the body element
*/
arr=[document.body,document.getElementById("sectionID"),
document.getElementById("DivId"),document.getElementById("PId"),
document.getElementById("spanId")];
/* Then trying to register handelers for both capturing and bubbling phases
*/
function listener(node){
node.addEventListener( ev, handler, bool )
/* ev :event (click), handler : logging the event associated with
the target, bool: capturing/bubbling phase */
}
ev="click";
bool=true; // Capturing phase
arr.forEach(listener);
bool=false; // Bubbling phase
/* Notice that both capturing and bubbling
include the at_target phase, that's why you'll get two `at_target` phases in
the log */
arr.forEach(listener);
<section ID="sectionID">
<div id="DivId">
<p id="PId">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis <span id="spanId">CLICK ME </span> imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.
</p>
</div>
</section>