Let's take a look at a JavaScript event bubbling example. There is a button in the div element, and they are all bound to a click event, which is a precondition for event bubbling. When you click on the button, there will be two warning boxes, one for the button's click event, and the other for the DIV's Click event. You just clicked on the button,div element and triggered the Click event, which is caused by event bubbling.
vardiv = document.getElementById ("mydiv"); Div.addeventlistener ("Click",function(Event) {alert ("This is div click"); }); varBTN = document.getElementById ("btn"); Btn.addeventlistener ("Click",function(Event) {alert ("This is button click"); }); </script></body>Now that you know what time bubbles are, how do you avoid this? (In general, we do not want the side effects of event bubbling)
1. Use Stoppropagation (). You only need to add this method of event when the button event is bound above. As shown below:
function (event) { alert ("This is button click"); Event.stoppropagation (); });
This time only triggers the button's Click event, and the DIV's Click event does not fire.
The above method is the simplest and smallest of changes. There is no better way to do it!!!
2. Use the event delegate. An event delegate is to define an event not directly on the target element, but on its outer node. This is actually achieved by using event bubbling technology.
var div = document.getElementById ("mydiv"); Div.addeventlistener (function (event) { switch (event.target.id) { case "Mydiv": alert ("The is div click"); Break ; Case "BTN": alert ("This is button click"); Break ; } });
Only one click event is triggered at this time.
The event delegate has more than one benefit:
1. Reduce the number of DOM operations and improve performance.
2. The entire page consumes less memory and improves performance.
3. If a button is removed, you do not have to worry about forgetting the bind event that removed the button.
Javascript Event Bubbling