所谓的事件冒泡,就是点击完内层元素后,事件依次向外层延伸。

示例如下:

代码片段:

<script src="http://www.cnblogs.com/scripts/jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// 为span元素绑定click事件
$('span').bind("click",function(){
   var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";
   $('#msg').html(txt);
});
// 为div元素绑定click事件
$('#content').bind("click",function(){
     var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>";
   $('#msg').html(txt);
});
// 为body元素绑定click事件
$("body").bind("click",function(){
   var txt = $('#msg').html() + "<p>body元素被点击.<p/>";
   $('#msg').html(txt);
});
})
</script>
</head>
<body>
<div >
外层div元素
<span>内层span元素</span>
外层div元素
</div>

<div ></div>

阻止冒泡的方法

// 为span元素绑定click事件
$('span').bind("click",function(event){
   var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";
   $('#msg').html(txt);
   event.stopPropagation();    // 阻止事件冒泡
});

或者:

// 为span元素绑定click事件
$('span').bind("click",function(event){
   var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";
   $('#msg').html(txt);
   return false;
});

另外:

event.preventDefault();

用于阻止默认行为,如表单提交等。

return false;同样也可以用于阻止默认行为。

相关文章:

  • 2021-08-25
  • 2021-06-20
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2022-12-23
  • 2021-08-12
  • 2021-07-08
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2021-12-17
相关资源
相似解决方案