简体   繁体   中英

Behaviour of Bubbling and Capturing Phase

Could somebody please explain the bubbling and capturing phase with this code according to output of the 4 cases in code , on clicking div2 and div1

http://jsfiddle.net/JuKmM/9/

code:

function doSomething2(){
 console.log("div 1 clicked");
}

var element1=document.getElementById('div_1');
var element2=document.getElementById('div_2');

element1.addEventListener('click',doSomething2,false);
element2.addEventListener('click',doSomething,true);

//element1.addEventListener('click',doSomething2,false);
//element2.addEventListener('click',doSomething,false);

//element1.addEventListener('click',doSomething2,true);
//element2.addEventListener('click',doSomething,true);

//element1.addEventListener('click',doSomething2,true);
//element2.addEventListener('click',doSomething,false);

function doSomething(){
console.log("div2 clicked");
}

From the MDN documentation :

useCapture Optional

If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. If not specified, useCapture defaults to false.

You're setting up the handler for "div_1" such that it does not use capture, and the handler for "div_2" such that it does , though since it's got no children that doesn't matter much. Thus:

  • A click on the blue part ("div_1") triggers only the handler on that element.
  • A click on the red part ("div_2") triggers the handler for that element. The event then bubbles up the DOM to "div_1", and that handler is triggered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM