阻止事件冒泡,阻止默认事件,event.stopPropagation()和event.preventDefault(),return false的区别

今天来看看前端的冒泡和事件默认事件如何处理

1.event.stopPropagation()方法

这是阻止事件的冒泡方法,不让事件向documen上蔓延,但是默认事件任然会执行,当你掉用这个方法的时候,如果点击一个连接,这个连接仍然会被打开,

2.event.preventDefault()方法

这是阻止默认事件的方法,调用此方法是,连接不会被打开,但是会发生冒泡,冒泡会传递到上一层的父元素;

3.return false  ;

这个方法比较暴力,他会同事阻止事件冒泡也会阻止默认事件;写上此代码,连接不会被打开,事件也不会传递到上一层的父元素;可以理解为return false就等于同时调用了event.stopPropagation()和event.preventDefault()

4.我们来看看几组demo,使用jquery进行DOM操作

这是html代码,div里面套了一个a标签,连接到百度

[html]  view plain  copy
  1. <div class="box1">  
  2.             <a href="http://www.baidu.com" target="_blank"></a>  
  3.         </div>  
css代码,a标签占父元素的空间的1/4,背景颜色为红色;

[html]  view plain  copy
  1. .box1{  
  2.                 height: 200px;  
  3.                 width: 600px;  
  4.                 margin: 0 auto;  
  5.             }  
  6.             .box1 a{  
  7.                 display: block;  
  8.                 height: 50%;  
  9.                 width: 50%;  
  10.                 background:red;  
  11.             }  


下面来看js代码,第一种 

[html]  view plain  copy
  1. //不阻止事件冒泡和默认事件  
  2.               
  3.             $(".box1").click(function(){  
  4.                 console.log("1")//不阻止事件冒泡会打印1,页面跳转;               
  5.             });  



第二种

[html]  view plain  copy
  1. //阻止冒泡  
  2.             $(".box1 a").click(function(event){  
  3.                 event.stopPropagation();//不会打印1,但是页面会跳转;              
  4.   
  5.             });  
  6.               
  7.             $(".box1").click(function(){  
  8.                 console.log("1")                  
  9. });  




 
 
 
  
  
 

第三种

[html]  view plain  copy
  1. $(".box1 a").click(function(event){           
  2. //阻止默认事件  
  3. event.preventDefault();//页面不会跳转,但是会打印出1,  
  4. });  
  5.               
  6. $(".box1").click(function(){  
  7. console.log("1");                 
  8. });  



 
  
  
 

第四种

[html]  view plain  copy
  1. $(".box1").click(function(){  
  2. console.log("1")  
  3. });           
  4. //阻止冒泡  
  5. $(".box1 a").click(function(event){  
  6. event.stopPropagation();              
  7. //阻止默认事件  
  8. event.preventDefault() //页面不会跳转,也不会打印出1  
  9. })  



第五种

[html]  view plain  copy
  1. $(".box1").click(function(){  
  2.                 console.log("1")                  
  3.             });                                   
  4. $(".box1 a").click(function(event){  
  5.                 return false;  //页面不会跳转,也不会打印出1,等于同时调用了event.stopPropagation()和event.preventDefault()  
  6.   
  7. });  

猜你喜欢

转载自blog.csdn.net/weixin_39717076/article/details/80074030