Skip to content

Instantly share code, notes, and snippets.

@caok
Created February 19, 2014 06:14
Show Gist options
  • Save caok/9086913 to your computer and use it in GitHub Desktop.
Save caok/9086913 to your computer and use it in GitHub Desktop.
jquery 事件冒泡
冒泡事件就是点击子节点,会向上触发父节点,祖先节点的点击事件。
下面是html代码部分:
<body>
<div id="content">
外层div元素
<span>内层span元素</span>
外层div元素
</div>
<div id="msg"></div>
</body>
对应的jQuery代码如下:
<script type="text/javascript">
$(function(){
// 为span元素绑定click事件
$('span').bind("click",function(){
var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";//获取html信息
$('#msg').html(txt);// 设置html信息
});
// 为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>
当点击span时,会触发div与body 的点击事件。点击div时会触发body的点击事件。
JQuery 提供了两种方式来阻止事件冒泡。
方式一:event.stopPropagation();
$("#div1").mousedown(function(event){
event.stopPropagation();
});
方式二:return false;
$("#div1").mousedown(function(event){
return false;
});
但是这两种方式是有区别的。
return false 不仅阻止了事件往上冒泡,而且阻止了事件本身。
event.stopPropagation() 则只阻止事件往上冒泡,不阻止事件本身。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment