Contents
  1. 1. 什么是事件冒泡
  2. 2. 事件冒泡的作用
  3. 3. 阻止事件冒泡
  4. 4. 阻止默认行为
  5. 5. 合并阻止操作

什么是事件冒泡

在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。

事件冒泡的作用

事件冒泡允许多个操作被集中处理(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子级元素上),它还可以让你在对象层的不同级别捕获事件。

阻止事件冒泡

事件冒泡机制有时候是不需要的,需要阻止掉,通过 event.stopPropagation() 来阻止

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$(function(){
var $box1 = $('.father');
var $box2 = $('.son');
var $box3 = $('.grandson');
$box1.click(function() {
alert('father');
});
$box2.click(function() {
alert('son');
});
$box3.click(function(event) {
alert('grandson');
event.stopPropagation();
});
$(document).click(function(event) {
alert('grandfather');
});
})
......
<div class="father">
<div class="son">
<div class="grandson"></div>
</div>
</div>

阻止默认行为

阻止表单提交

1
2
3
$('#form1').submit(function(event){
event.preventDefault();
})

合并阻止操作

实际开发中,一般把阻止冒泡和阻止默认行为合并起来写,合并写法可以用

1
2
3
4
5
// event.stopPropagation();
// event.preventDefault();
// 合并写法:
return false;