DIV CSS 佈局教程網

jQuery 防止事件冒泡的方法
編輯:JQuery特效代碼     

所謂冒泡事件,就是點擊子節點時,會向上觸發父節點、祖先節點的點擊事件。下面先來看看問題是怎麼產生的。

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 的點擊事件。這就是冒泡。

如何防止冒泡?

在事件處理函數中調用 event.stopPropagation(); 即可阻止事件繼續向上冒泡:

<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

其實還有更簡潔的寫法——直接 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>

小結:return false 會同時阻止瀏覽器默認事件與冒泡;而 event.preventDefault(); 只能單獨阻止默認事件,event.stopPropagation(); 只能單獨阻止冒泡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved