1、return false:可以阻止默认事件和冒泡事件
2、event.stopPropagation/IE下event.cancelBubble = true;:可以阻止冒泡事件但是允许默认事件
3、event.preventDefault();/IE下event.returnValue = false:可以阻止默认事件但是允许冒泡事件
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>jQuery阻止冒泡</title> 6 <style> 7 .div1{ 8 width: 140px; 9 border: 1px solid blue; 10 } 11 .div2{ 12 width: 100px; 13 height: 100px; 14 margin: 20px; 15 border: 1px solid red; 16 } 17 </style> 18 </head> 19 <body> 20 <div class="div1"> 21 <div class="div2"> 22 点我呀!!!! 23 </div> 24 </div> 25 26 <a href="http:www.baidu.com" id="a1">百度</a> 27 28 <script src="../js/jquery/jquery.min.js"></script> 29 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> 30 <script> 31 $(‘.div1‘).bind(‘click‘,function(){ 32 alert("div1"); 33 }); 34 $(‘.div2‘).bind(‘click‘,function(){ 35 alert("div2"); 36 // return false;//也可以通过return false 阻止冒泡 37 if(window.event){//IE下阻止冒泡 38 event.cancelBubble = true; 39 }else{ 40 event.stopPropagation(); 41 } 42 }); 43 $(‘#a1‘).bind(‘click‘,function(){ 44 if(window.event){//IE下阻止默认事件 45 event.returnValue = false; 46 }else{ 47 event.preventDefault(); 48 } 49 alert("我是链接"); 50 //return false;//如果不添加任何阻止事件,先弹框,后跳转,我们可以通过return false阻止跳转 51 }); 52 53 </script> 54 </body> 55 </html>
时间: 2024-10-10 17:42:36