阻止冒泡事件

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript"> 
$(document).ready(function(){ 


$('.one').click(function(e,v){ 
alert('one'); 
});             
$('.two').click(function(e,v){   
alert('two'); 
//阻止起泡取消下面的注释 
e.stopPropagation();
//或者使用这种方式
//return false;
}); 
$('.three').click(function(e){ 
alert('three'); 
//阻止起泡取消下面的注释 
 e.stopPropagation(); 
 //或者使用这种方式
//return false;

}); 
}); 
</script> 
</head>
<body>
<div class="one" style="width:300px;height:300px;background:yellow;">
   1111
   <div class="two" style="width:200px;height:200px;background:green;">
      2222
       <div class="three" style="width:100px;height:100px;background:grey;">
          3333
       </div>


   </div>


</div>


</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

可以在这里在线调试 
http://www.w3cschool.cc/try/try.php?filename=tryjquery_hide

没看懂的继续向下看。

1.什么是事件冒泡:

页面上有好多事件,也可以多个元素响应一个事件.假如:

<BODY onclick="alert('aaa');">
<div onclick="alert('bbb');">
 <a href="#" class="cooltip" title="这是我的超链接提示1。" onclick="alert('ddd');> 

   提示

  </a>
</div>
</BODY>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

上面这段代码一共有三个事件,body,div,a都分别绑定了单击事件。在页面中当单击a标签会连续弹出3个提示框。这就是事件冒泡引起的现象。事件冒 泡的过程是:a –> div –> body 。a冒泡到div冒泡到body

2.事件冒泡引发的问题。

本来在上面的代码中只想触发元素的onclick事件,然而

3.jQuery对这个问题进行了必要的扩展和封装.

  $("element").bind("click",function(event){ 

     //event为事件对象

    //.........

   event.stopPropagation();   //停止事件冒泡

  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4.阻止默认行为

网页中的某些元素是有自己的默认行为的,比如果超链接单节后需要跳转,提交按钮点击后需要提交表单,有时需要阻止这些行为,也就是默认行为。

jquery中可用用preventDefault()的方法来阻止元素的默认行为.

$('#submit').bind('click',function(event){

   var username = $('#username').val();

   if(username==""){

     alert('用户名不能为空!');

     event.preventDefault();   //阻止默认行为

   }

})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

5.jquery中对冒泡和默认行为的阻止方法同样也可以改写,改写后能够达到同样的效果

event.preventDefault(); 改写为: return false;

event.stopPropagation(); 改写为: return false; 
参考: 
http://www.cnblogs.com/zhujie/archive/2011/02/11/1951533.html 
http://www.jb51.net/article/34914.htm

猜你喜欢

转载自blog.csdn.net/qq_38122518/article/details/80238633