js冒泡、捕獲事件及阻止冒泡方法詳細總結

來源:互聯網
上載者:User

javascript, jquery的事件中都存在事件冒泡和事件捕獲的問題,下面將兩種問題及其解決方案做詳細總結。

事件冒泡是一個從子節點向祖先節點冒泡的過程;

事件捕獲剛好相反,是從祖先節點到子節點的過程。

給一個jquery點擊事件的例子:

代碼如下:
複製代碼 代碼如下:
<!DOCTYPE html>
<meta charset="utf-8">
<title>test</title>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
$('#clickMe').click(function(){
alert('hello');
});
$('body').click(function(){
alert('baby');
});
});
</script>
</head>
<body>
<div style="width:100px;height:100px;background-color:red;">
<button type="button" id="button2">click me</button>
<button id="clickMe">click</button>
</div>
</body>
</html>

事件冒泡現象:點擊 “id=clickMe” 的button,會先後出現“hello” 和 “baby” 兩個彈出框。

分析:當點擊 “id=clickMe” 的button時,觸發了綁定在button 和 button 父元素及body的點擊事件,所以先後彈出兩個框,出現所謂的冒泡現象。


事件捕獲現象:點擊沒有綁定點擊事件的div和 “id=button2” 的button, 都會彈出 “baby” 的對話方塊。


在實際的項目中,我們要阻止事件冒泡和事件捕獲現象。

阻止事件冒泡方法:

法1:當前點擊事件中return false;
複製代碼 代碼如下:
$('#clickMe').click(function(){
alert('hello');

return false;
});

法2:
複製代碼 代碼如下:
$('#clickMe').click(function(event){
alert('hello');

var e = window.event || event;

if ( e.stopPropagation ){ //如果提供了事件對象,則這是一個非IE瀏覽器
e.stopPropagation();
}else{
//相容IE的方式來取消事件冒泡
window.event.cancelBubble = true;
}
});

貌似捕獲事件不能被阻止

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.