What is the use of event bubbling and event capturing?
If you click on an element, for example a link which is structured on the page as follows:
- BODY
- DIV
- A
then not only A gets the onclick event but all the elements UNDER it too. The first round is the capturing phase which goes from bottom to top, every element gets the onclick event and has the ability to break the event. When capturing is over the targeting phase occurs - that is the topmost element that was clicked. And afterwards bubbling happens, that's almost the same as capturing but this time it goes backwards, from top to bottom. So in the following example after a click not 1 onclick event occurs but actually 5 (2 x capturing, 1 x targeting, 2 x bubbling).
Capturing phase
v ---BODY--- :onclick, break event?
v --DIV-- :onclick, break event?
targeting phase
v -A- :onclick, break event?
bubbling phase
v --DIV-- :onclick, break event?
v ---BODY--- :onclick, break event?
精彩评论