事件冒泡,事件委托与如何阻止冒泡
1.事件冒泡
<div class="father">
<div class="son">儿子</div>
</div>
<script>
var son = document.querySelector('.son');
son.addEventListener('click',function(e){
alert('son');
},false);
var father = document.querySelector('.father');
son.addEventListener('click',function(e){
alert('father');
},false);
document.addEventListener('click',function(e){
alert('document');
},false);
</script>
点击son后,会层层向上,依次弹出son,father和document,这就是事件的冒泡。
2.使用stopPropagation()阻止冒泡
<div class="father">
<div class="son">儿子</div>
</div>
<script>
var son = document.querySelector('.son');
son.addEventListener('click',function(e){
alert('son');
e.stopPropagation();// 阻止事件冒泡 ie不兼容
e.cancelBubble=true;//ie兼容方法
},false);
var father = document.querySelector('.father');
son.addEventListener('click',function(e){
alert('father');
},false);
document.addEventListener('click',function(e){
alert('document');
},false);
</script>
3.事件委托(事件代理)
事件委托也称为事件代理、事件委派
(1)原理
不是每个子节点单独设置事件监听器,而是事件监听器设置在其父节点上,然后利用冒泡原理影响设置每个子节点
(2)作用
只操作了一次DOM,提高了程序的性能。
(3)举例
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
<script>
var ul = document.querySelector('ul');
ul.addEvrntListener('click',function(e){
e.target.style.backgroundColor='black'//点击哪个li,哪个的背景色变黑
})
</script>
不用给每个li添加事件监听,只需要给父元素ul添加事件监听即可。