In Javascript
, event bubbling is generated by the node, and then affects the parent node, rising step by step, and finally slowly affecting the entire page, but sometimes we want to prevent event bubbling from happening. Or even the occurrence of the event itself? This article will take you to find out together.
1. Prevent events from bubbling up
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .boxA { overflow: hidden; width: 300px; height: 300px; margin: 100px auto; background-color: blue; text-align: center; } .boxB { width: 200px; height: 200px; margin: 50px; background-color: green; line-height: 200px; color: #fff; } </style> </head> <body> <div class="boxA"> <div class="boxB">boxB</div> </div> <script> var boxA = document.querySelector('.boxA'); var boxB = document.querySelector('.boxB'); boxA.onclick = function (e) { console.log('我被点击了boxA'); }; boxB.onclick = function (e) { e.cancelBubble=true; //不冒泡 console.log('我被点击了boxB'); }; </script> </body> </html>
2. Prevent events from occurring
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <form action="http://www.php.cn" method="POST"> <button type="submit">按钮1</button> </form> <body> <script> const btn=document.querySelector("button"); console.log(btn); btn.addEventListener("click",function(e){ e.preventDefault(); }); </script> </body> </html>
Recommended: "2021 js interview questions and answers (large summary)"
The above is the detailed content of How Javascript prevents events from bubbling and the event itself from occurring. For more information, please follow other related articles on the PHP Chinese website!