首页 > 解决方案 > 嵌套按钮触发两次引导折叠事件

问题描述

我有一个collapse包含多个其他collapse元素的 Bootstrap 元素,当collapse单击(显示或隐藏)时,我想捕获该事件。

我遇到的问题是,collapse如果单击嵌套折叠按钮(对于父折叠和单击折叠),事件会被触发两次。

这是显示问题的演示:https ://jsfiddle.net/6nbsp9c1/2/

单击嵌套按钮时,事件被触发两次,我该如何解决?

标签: javascripthtmljquerybootstrap-4

解决方案


您需要使用stopImmediatePropagation来确保事件不会被多次调用。

Event 接口的stopImmediatePropagation()方法防止调用同一事件的其他监听器。

现场演示:

$(document).on('show.bs.collapse hide.bs.collapse', '.collapse', function(e) {
  e.stopImmediatePropagation(); //use this
  console.log('event triggered');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
  Link with href
</a>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    test test test
    <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample2" role="button" aria-expanded="false" aria-controls="collapseExample2">
      Link with href
    </a>
    <div class="collapse" id="collapseExample2">
      <div class="card card-body">
        test test test
      </div>
    </div>
  </div>


  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>


推荐阅读