jQuery如何防止這種冒泡事件發(fā)生
冒泡事件就是點擊子節(jié)點,事件會向上傳遞,最后觸發(fā)父節(jié)點,祖先節(jié)點的點擊事件。
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時,會觸發(fā)div與body 的點擊事件。點擊div時會觸發(fā)body的點擊事件。
如何防止這種冒泡事件發(fā)生呢?修改如下:
<script type="text/javascript">
$(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);
});
})
</script>
有時候點擊提交按鈕會有一些默認事件。比如跳轉到別的界面。但是如果沒有通過驗證,就不應該跳轉。這時候可以通過設置event.preventDefault(); 阻止默認行為。下面是案例:
<script type="text/javascript">
$(function(){
$("#sub").bind("click",function(event){
var username = $("#username").val(); //獲取元素的值,val() 方法返回或設置被選元素的值。
if(username==""){ //判斷值是否為空
$("#msg").html("<p>文本框的值不能為空.</p>"); //提示信息
event.preventDefault(); //阻止默認行為 ( 表單提交 )
}
})
})
</script>
html部分:
<body>
<form action="test.html">
用戶名:<input type="text" id="username" /><br/>
<input type="submit" value="提交" id="sub"/>
</form>
<div id="msg"></div>
</body>
還有一種防止默認行為的方法就是return false。效果一樣。代碼如下:
<script type="text/javascript">
$(function(){
$("#sub").bind("click",function(event){
var username = $("#username").val();
if( username == "" ){
$("#msg").html("<p>文本框的值不能為空.</p>");
return false;
}
})
})
</script>
同理,上面的冒泡事件也可以通過return false來處理。
<script type="text/javascript">
$(function(){
$('span').bind("click",function(event){
var txt = $('#msg').html() + "<p>內層span元素被點<p/>";
$('#msg').html(txt);
return false;
});
$('#content').bind("click",function(event){
var txt = $('#msg').html() + "<p>外層div元素被點<p/>";
$('#msg').html(txt);
return false;
});
$("body").bind("click",function(){
var txt = $('#msg').html() + "<p>body元素被點<p/>";
$('#msg').html(txt);
});
})
</script>
jQuery對DOM的事件觸發(fā)具有冒泡特性。有時利用這一特性可以減少重復代碼,但有時候我們又不希望事件冒泡。這個時候就要阻止 jQuery.Event冒泡。
相關文章
jquery實現(xiàn)效果比較好的table選中行顏色
這篇文章主要介紹了jquery table選中行顏色實現(xiàn)代碼,需要的朋友可以參考下2014-03-03
jQuery 選擇表格(table)里的行和列及改變簡單樣式
本文只是介紹如何用jQuery語句對表格中行和列進行選擇以及一些簡單樣式改變,希望它可以對jQuery表格處理的深層學習提供一些幫助2012-12-12
jQuery ajax serialize()方法的使用以及常見問題解決
使用ajax時,常常需要拼裝input數(shù)據(jù)為'name=abc&sex=1'這種形式,用JQuery的serialize方法可以輕松的完成這個工作接下來介紹jQuery ajax - serialize() 方法定義和用法,感興趣的朋友可以了解下啊,希望本文對你有所幫助2013-01-01
jQuery Validate表單驗證插件實現(xiàn)代碼
這篇文章主要介紹了jQuery Validate表單驗證插件實現(xiàn)代碼,需要的朋友可以參考下2017-06-06

