如何防止jQuery事件冒泡到父元素?
为了防止jQuery事件冒泡到父元素,请使用stopPropogation()
方法。该stopPropagation()
方法停止将事件冒泡到父元素,从而防止任何父处理程序收到该事件的通知。
示例
您可以尝试运行以下代码,以防止jQuery事件冒泡至父元素-
<html> <head> <title>jQuery stopProagation() method</title> <script src = "https://cdn.staticfile.org/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:20px; padding:20px; 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:green;"> OUTER BOX <div id = "div2" style = "background-color:gray;"> INNER BOX </div> </div> </body> </html>