The stopPropagation function is used in JavaScript to stop event propagation.
Events in JS are bubble by default, which are propagated layer by layer. You can use the stopPropagation () function to stop the propagation of events at the DOM level. For example:
HTML code:
<! DOCTYPE html>
DOM is propagated layer by layer, so clicking the button also spreads to the body layer, so the click of the body layer also responds. Two warning boxes are displayed, button and body.
Added stopPropagation ()
Var button = document. getElementsByTagName ('button ') [0]; button. onclick = function (event) {alert ('button click'); // stop the DOM event level propagation event. stopPropagation () ;}; document. body. onclick = function (event) {alert ('body click ');}
The stopPropagation () Stop event propagation function is used in the click event processing function of the button. Therefore, the body cannot be propagated after a warning box from the button click event is displayed, the body warning box will not be displayed again, and only one warning box will be displayed in the result.
Many children's shoes often neglect the feature of DOM events spreading layer by layer when writing JavaScript, leading to program exceptions. If you need more in-depth knowledge, you can find information about JS event bubbling.
How to prevent javascript event bubbling
1. cancelBubble (html dom Event object attribute): If the Event handle wants to prevent the Event from spreading to an inclusive object, it must be set to true.
2. stopPropagation (html dom Event object method): terminates further propagation of an Event in the capture, target processing, or blister phase of the propagation process. After this method is called, the handler for processing the event on the node will be called, and the event will not be assigned to other nodes.
3. preventDefault (html dom Event object method) notifies the browser not to perform the default action associated with the Event.
Example:
Function stopBubble (e)
{
If (e & e. stopPropagation)
E. stopPropagation ()
Else
Window. event. cancelBubble = true
}
Put this stopBubble (e) function in the function that you want to stop event bubbles to prevent event bubbles.
How to Prevent the bubbling mechanism of javascript events
This. style. border = '1px solid white';} var all2 = document. getElementsByTagName ('div ') [1]. getElementsByTagName ('*'); for (var I = 0, n = all2.length; I <n; ++ I) {all2 [I]. onmouseover = function (e) {this. style. border = '1px solid red'; if (e) // stop event bubbling e. stopPropagation (); elsewindow. event. cancelBubble = true; log. value = 'cursor: '+ this. nodeName;}; all2 [I]. onmouseout = function (e) {this. style. border = '1px solid white ';}}} window. onload = init; //] </script