事件冒泡是指點擊某個元素時,事件會一層層往上傳到父元素。有時這並不是我們想要的,這時就要阻止它。先看 HTML 結構:
<body>
<div id="content">
外層div元素
<span>內層span元素</span>
外層div元素
</div>
<div id="msg"></div>
</body>
對應的 jQuery:
<script type="text/javascript">
$(function(){
$('span').bind("click",function(){
var txt = $('#msg').html() + "<p>內層span元素被點擊.<p/>";
$('#msg').html(txt);
});
$('#content').bind("click",function(){
var txt = $('#msg').html() + "<p>外層div元素被點擊.<p/>";
$('#msg').html(txt);
});
$("body").bind("click",function(){
var txt = $('#msg').html() + "<p>body元素被點擊.<p/>";
$('#msg').html(txt);
});
})
</script>
此時點擊 span,會連帶觸發 div 與 body 的點擊事件;點擊 div 也會觸發 body 的事件。要避免這種連鎖反應,可以加上 stopPropagation():
$(function(){
$('span').bind("click",function(event){
var txt = $('#msg').html() + "<p>內層span元素被點擊.<p/>";
$('#msg').html(txt);
event.stopPropagation(); // 阻止事件冒泡
});
$('#content').bind("click",function(event){
var txt = $('#msg').html() + "<p>外層div元素被點擊.<p/>";
$('#msg').html(txt);
event.stopPropagation(); // 阻止事件冒泡
});
$("body").bind("click",function(){
var txt = $('#msg').html() + "<p>body元素被點擊.<p/>";
$('#msg').html(txt);
});
})
除了冒泡,表單還有「預設行為」需要處理。例如提交按鈕在未通過驗證時不該跳頁,這時可用 event.preventDefault() 阻止:
$(function(){
$("#sub").bind("click",function(event){
var username = $("#username").val();
if(username==""){
$("#msg").html("<p>文本框的值不能為空.</p>");
event.preventDefault(); // 阻止默認行為 ( 表單提交 )
}
})
})
其實 return false 也能達到相同效果,它同時阻止了冒泡與預設行為:
$(function(){
$("#sub").bind("click",function(event){
var username = $("#username").val();
if(username==""){
$("#msg").html("<p>文本框的值不能為空.</p>");
return false;
}
})
})
小結一下:stopPropagation() 阻止事件往父層傳遞,preventDefault() 阻止表單提交等預設動作,而 return false 則是兩者兼備的簡便寫法。