事件传播模型:事件捕获和事件冒泡两个过程
即事件先到达根元素,再从根元素一层一层向下传播到目标元素,然后再一层一层向上传到根元素。
<div id='one'>
one
<div id='two'>
two
<div id='three'>
three
<div id='four'>
four
</div>
</div>
</div>
</div>
<script type='text/javascript'>
var one=document.getElementById('one');
var two=document.getElementById('two');
var three=document.getElementById('three');
var four=document.getElementById('four');
one.addEventListener('click',function(){
alert('one');
},true);
two.addEventListener('click',function(){
alert('two');
},true);
three.addEventListener('click',function(){
alert('three');
},true);
four.addEventListener('click',function(){
alert('four');
},true
这几个事件处理程序都是在事件捕获阶段触发。
单击one:目标元素是one,输出one
单击two:目标元素是two,接收事件的顺序是one->two->one,因为只在捕获阶段处理事件,因此输出的是one two
单击three:目标元素是three,接收事件的顺序是one->two->three->two->one,因为只在捕获阶段处理事件,因此输出 one two three
单击four:目标元素是four,接收事件的顺序是one->two->three->four->three->two->one,因为只在捕获阶段处理事件,因此输出的是one two three four
one.addEventListener('click',function(){
alert('one');
},false);
two.addEventListener('click',function(){
alert('two');
},false);
three.addEventListener('click',function(){
alert('three');
},false);
four.addEventListener('click',function(){
alert('four');
},false);
单击one:输出one
单击two:输出two one
单击three:输出three two one
单击four:输出four three two one
one.addEventListener('click',function(){
alert('one');
},true);
two.addEventListener('click',function(){
alert('two');
},false);
three.addEventListener('click',function(){
alert('three');
},false);
four.addEventListener('click',function(){
alert('four');
},true);
单击four:输出one four three two
one.addEventListener('click',function(){
alert('one capture');
},true);
two.addEventListener('click',function(){
alert('two bubble');
},false);
two.addEventListener('click',function(){
alert('two capture');
},true);
three.addEventListener('click',function(){
alert('three bubble');
},false);
four.addEventListener('click',function(){
alert('four capture');
},true);
事件的执行次数:绑定了几个事件就执行几次
这个分两种情况讨论:
(1)若目标元素是two,目标事件处理程序按添加事件的顺序执行,其他元素的按先捕获后冒泡
则输出:one capture--two bubble--two capture
(2)若目标元素不是two,假设单击four
则输出是:one capture--two capture--four capture--three bubble--two bubble