收听 Bootstrap 崩溃 shown/hidden 事件?

Listening to the Bootstrap collapse shown/hidden events?

我有一个 Bootstrap 5 accordion 看起来像这样:

<div class="accordion" id="my_accordion">
  <div class="accordion-item">
    <h2 class="accordion-header" id="heading_bar">
      <button class="accordion-button collapsed bg-light my-collapse" type="button" data-bs-toggle="collapse" data-bs-target="#collapse_bar" aria-expanded="false" aria-controls="collapse_bar">Bar</button>
    </h2>
    <div id="collapse_bar" class="accordion-collapse collapse" aria-labelledby="heading_bar" data-bs-parent="#my_accordion">
      <div class="accordion-body">
        ...
      </div>
    </div>
  </div>
</div>

我正在尝试收听 shownhidden 事件,如所述 in the collapse docs:

return $('button.my-collapse[data-bs-toggle="collapse"]').on('shown.bs.collapse', function(e) {
  console.log("This is not fired...")
});

但由于某些原因事件没有触发。我知道我有正确的选择器,因为如果我将 shown.bs.collapse 更改为 click,就会发生一个事件。

知道发生了什么吗?

顺便说一句,我的逻辑似乎也适用于这样的标签:

<div class="card">
  <div class="card-header">
    <ul class="nav nav-tabs card-header-tabs" id="debug_tab" role="tablist">
      <li class="nav-item"><a class="nav-link my-tab" id="products-tab" data-bs-toggle="tab" href="#foo" role="tab" aria-controls="foo" aria-selected="false">Foo</a></li>
    </ul>
  </div>
  <div class="card-body">
    ...
  </div>
</div>

当我这样听的时候:

return $('a.my-tab[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
  console.log("This is fired...")
});

试试这个:

var myCollapsible = document.getElementById('collapse_bar')
myCollapsible.addEventListener('hidden.bs.collapse', function () {
  console.log("Hidden")
});
myCollapsible.addEventListener('shown.bs.collapse', function () {
  console.log("Shown")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

<div class="accordion" id="my_accordion">
  <div class="accordion-item">
    <h2 class="accordion-header" id="heading_bar">
      <button class="accordion-button collapsed bg-light my-collapse" type="button" data-bs-toggle="collapse" data-bs-target="#collapse_bar" aria-expanded="false" aria-controls="collapse_bar">Bar</button>
    </h2>
    <div id="collapse_bar" class="accordion-collapse collapse" aria-labelledby="heading_bar" data-bs-parent="#my_accordion">
      <div class="accordion-body">
        ...
      </div>
    </div>
  </div>
</div>