JavaScript 阻止事件冒泡

阻止事件冒泡

场景:列表项中,有一个按钮。点击按钮触发购买行为跳转购买页,点击其他部分跳转商品详情页。因此需要在点击按钮时,阻止事件冒泡。

<body>
  <div class="father" onclick="clickHandle1(event)">
    <div class="son" onclick="clickHandle2(event)">
      <a href="http://www.baidu.com" target="_blank">链接</a>
    </div>
  </div>
  <script>
    function clickHandle1(e) {
      console.log('father');
    }

    function clickHandle2(e) {
      console.log('son');
    }
  </script>
  <style>
    .father {
      width: 400px;
      height: 400px;
      background: red;
    }

    .son {
      width: 200px;
      height: 200px;
      background: green;
    }
  </style>
</body>

点击链接,会跳转链接(a 标签默认行为),并且在控制台打印出“son”和“father”(事件冒泡)。

在 a 标签的点击事件中,调用 event.preventDefault() 或 return false 可以阻止跳转。

结论

方法 event.stopPropagation() event.preventDefault() return false
阻止事件冒泡 不能
阻止默认行为 不能
posted @ 2020-05-21 17:30  水流云在  阅读(158)  评论(0编辑  收藏  举报