事件冒泡
什么是事件冒泡
在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。
事件冒泡的作用
事件冒泡允许多个操作被集中处理(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子级元素上),它还可以让你在对象层的不同级别捕获事件。
阻止事件冒泡
事件冒泡机制有时候是不需要的,需要阻止掉,通过 event.stopPropagation() 来阻止。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript">
// 事件冒泡,往父级传递
// 就是传递给父级标签
$(function(){
$('.son').click(function(event){
alert(1);
event.stopPropagation();
// event 是发生事件的时候的事件对象,使用的时候通过第一个参数传进
})
$('.father').click(function(){
alert(2);
})
$('.grandfather').click(function(){
alert(3);
})
})
</script>
<style type="text/css">
.grandfather{
width: 300px;
height: 300px;
background-color: green;
position: relative;
}
.father{
width: 200px;
height: 200px;
background-color: #FFA500;
}
.son{
background-color: #00FFFF;
height: 100px;
width: 100px;
position: absolute;
left: 0;
top: 400px;
}
</style>
<title></title>
</head>
<body>
<div class="grandfather">
<div class="father">
<div class="son">
</div>
</div>
</div>
</body>
</html>
点击黄色的会出现2,3点击,蓝色不会出现2,3。因为添加event事件阻止其冒泡
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(function(){
$('#btn').click(function(){
$('.pop_con').fadeIn();
return false;
})
$(document).click(function(){
$('.pop_con').fadeOut();
})
$('.pop').click(function(){
return false;
})
$('.close').click(function(){
$('.pop_con').fadeOut();
})
})
</script>
<style type="text/css">
.pop{
position: fixed;
width: 500px;
height: 300px;
background-color: #fff;
border: 3px solid #000;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -150px;
z-index: 9999;
}
.mask{
position: fixed;
width: 100%;
height: 100%;
background-color: #000;
opacity: 0.3;
filter: alpha(opacity=30);
left: 0;
top: 0;
z-index: 9990;
}
.pop_con{
display: none;
}
.close{
float: right;
font-size: 16px;
}
</style>
<title></title>
</head>
<body>
<input type="button" name="" id="btn" value="弹出" />
<div class="pop_con">
<div class="pop">
弹框里面的文字
投资金额
<input type="text" name="" id="" value="" />
<a href="#" id="close" class="close">×</a>
</div>
<div class="mask">
</div>
</div>
</body>
</html>
事件委托
事件委托就是利用冒泡的原理,把事件加到父级上,通过判断事件来源的子集,执行相应的操作,事件委托首先可以极大减少事件绑定次数,提高性能;其次可以让新加入的子元素也可以拥有相同的操作。
一般绑定事件的写法
$(function(){
$ali = $('#list li');
$ali.click(function() {
$(this).css({background:'red'});
});
})
...
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
事件委托的写法
$(function(){
$list = $('#list');
$list.delegate('li', 'click', function() {
$(this).css({background:'red'});
});
})
...
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>