<div id="content">
外层div元素
<p>内层span元素</p>
外层div元素
</div>
<br/><br/>
<div id="msg"></div>
<script>
$(function(){
// 为span元素绑定click事件
$('p').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事件
$('#content').bind('click',function(){
var txt = $("#msg").html()+'<p>body元素被单击</p>';
$("#msg").html(txt);
});
});
</script>
停止事件冒泡
$('p').bind('click',function(event){
var txt = $("#msg").html()+'<p>内层span元素被单击</p>';
$("#msg").html(txt);
event.stopPropagation();
});
此外,阻止事件默认行为,比如提交表单时,在表单数据格式验证错误的时候直接阻止表单提交:
event.preventDefault();
也可以用 return false 来改写 停止时间冒泡和阻止事件默认行为。