js中事件冒泡和事件捕获

什么时候存在这种问题?
当一个行为触发了多个对象的事件时。
 
<body>
  <div class="fa">
    <div class="son1">
      <div class="son2"></div>
    </div>
  </div>
  <script type="text/javascript">
    var fa = document.getElementsByClassName('fa')[0];
    var son1 = document.getElementsByClassName('son1')[0];
    var son2 = document.getElementsByClassName('son2')[0];
    fa.addEventListener("click",function(e){console.log('fa');e.stopPropagation();},true);
    son1.addEventListener('click',function(){console.log('son1')},false);
    son2.addEventListener('click',function(){console.log('son2')},true);
  </script>
addEventListener第三个参数不写时默认为false,true代表在事件捕获阶段执行,false代表在事件冒泡阶段执行。
e.stopPropagation()可以让一个行为只执行一个对象的事件。
posted @ 2017-02-18 20:10  liululu  阅读(250)  评论(0编辑  收藏  举报