如何阻止 jQuery 中的事件冒泡到父元素?
要阻止事件冒泡到父元素,可以使用 stopPropagation() 方法。可以尝试运行以下代码,了解如何阻止事件冒泡到父元素 −
示例
<html> <head> <title>jQuery stopPropagation() method</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("div").click(function(event){ alert("This is : " + $(this).text()); event.stopPropagation(); }); }); </script> <style> div { margin:10px; padding:12px; border:2px solid #666; width:160px; } </style> </head> <body> <p>Click on any box to see the effect:</p> <div id = "div1" style = "background-color:blue;"> OUTER BOX <div id = "div2" style = "background-color:red;"> INNER BOX </div> </div> </body> </html>
广告