jQuery中的event.preventDefault()和event.stopPropagation()有什么区别?
stopPropogation()方法
要停止将事件冒泡到父元素,请使用stopPropagation()
方法。
示例
您可以尝试运行以下代码来学习如何使用stopPropogation()
方法:
<html> <head> <title>jQuery stopPropagation() method</title> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script type = "text/javascript" language = "javascript"> $(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>
preventDefault()方法
该preventDefault()
方法可防止浏览器执行默认操作。
示例
您可以尝试运行以下代码以在jQuery中运行event.preventDefault()方法:
<html> <head> <title>jQuery preventDefault() method</title> <script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("a").click(function(event){ event.preventDefault(); alert( "默认行为已禁用!" ); }); }); </script> </head> <body> <span>Click the following link and it won't work:</span> <a href = "https://www.qries.com">Qries</a> </body> </html>