Home > Article > Web Front-end > Example of using stopPropagation function to stop event propagation in JavaScript_javascript skills
Events in JS default to bubbling, propagating upward layer by layer. You can stop the propagation of events in the DOM hierarchy through the stopPropagation() function. Such as the following example:
HTML code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>stopPropagation()使用 - 琼台博客</title> </head> <body> <button>button</button> </body> </html> [/code] 没有加stopPropagation() [code] var button = document.getElementsByTagName('button')[0]; button.onclick=function(event){ alert('button click'); }; document.body.onclick=function(event){ alert('body click'); }
The DOM propagates upward layer by layer, so clicking the button button also propagates to the body layer, so the click on the body layer also responds. As a result, two warning boxes pop up, namely button and body.
Added stopPropagation()
var button = document.getElementsByTagName('button')[0]; button.onclick=function(event){ alert('button click'); // 停止DOM事件层次传播 event.stopPropagation(); }; document.body.onclick=function(event){ alert('body click'); }
The stopPropagation() is used in the button's click event processing function to stop the event propagation function. Therefore, after the warning box from the button click event pops up, it cannot be propagated to the body, and the body warning box will not pop up again. , the result is that the warning box is only discussed once.
When many children write JS, they often ignore the feature of DOM events propagating upward layer by layer, causing program abnormalities. If you need more in-depth knowledge, you can look for information about JS event bubbling.