e.preventDefault()是阻止默认事件的方法;
e.stopPropagation()是阻止事件冒泡;
return false;是既阻止事件冒泡又阻止默认事件;
以下是个阻止事件冒泡的小案例:
<!DOCTYPE html> <html> <head> <title>阻止冒泡</title> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> </head> <style type="text/css"> #div1{ width: 400px; height: 400px; background: #f00; } #div2{ width: 300px; height: 300px; background: #0f0; } #div3{ width: 200px; height: 200px; background: #00f; } #div4{ width: 100px; height: 100px; background: #f0f; } </style> <body> <div id="div1">我是div1 <div id="div2">我是div2 <div id="div3">我是div3 <div id="div4">我是div4</div> </div> </div> </div> <script type="text/javascript"> $(function(){ $("body").on(‘click‘, ‘#div1‘, function() { alert(‘我是div1‘) }).on(‘click‘, ‘#div2‘, function() { alert(‘我是div2‘) e.stopPropagation(); }).on(‘click‘, ‘#div3‘, function() { alert(‘我是div3‘) e.stopPropagation(); }).on(‘click‘, ‘#div4‘, function() { alert(‘我是div4‘) return false; }); }) </script> </body> </html>
效果图如下:
原文地址:https://www.cnblogs.com/myunYao/p/8874735.html
时间: 2024-10-10 21:53:06