阻止事件冒泡的三种手段
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://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> 30 <script> 31 $('.div1').bind('click',function(){ 32 alert("div1"); 33 }); 34 35 $('.div2').bind('click',function(event){ 36 alert("div2"); 37 //return false;//也可以通过return false 阻止冒泡 38 39 /*if(window.event && event.cancelBubble){//IE下阻止冒泡 40 event.cancelBubble = true; 41 }else{ 42 event.stopPropagation(); 43 }*/ 44 if(event && event.stopPropagation){ //W3C 45 event.stopPropagation(); 46 }else{ //IE下阻止冒泡 47 window.event.cancelBubble = true; 48 } 49 50 }); 51 $('#a1').bind('click',function(event){ 52 if(window.event){//IE下阻止默认事件 53 event.returnValue = false; 54 }else{ //W3C 55 event.preventDefault(); 56 } 57 58 alert("我是链接"); 59 // return false;//如果不添加任何阻止事件,先弹框,后跳转,我们可以通过return false阻止跳转 60 }); 61 62 </script> 63 </body> 64 </html>