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

示例如下:

代码片段:

<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 id="content">
外层div元素
<span>内层span元素</span>
外层div元素
</div>

<div id="msg"></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;同样也可以用于阻止默认行为。

posted on 2010-11-04 14:40  myjavawork  阅读(301)  评论(0编辑  收藏  举报