繁体   English   中英

为什么“show/shown/hide/hidden.bs.collapse”不会在我的嵌套折叠元素上触发?

[英]Why "show/shown/hide/hidden.bs.collapse" doesn't get triggered on my nested collapse element?

我有一个按钮。 单击按钮会折叠 div。 在那个折叠的 div 中有另一个按钮。 单击该按钮时,它会折叠另一个 div。

现在崩溃和一切正常,我的问题在于事件。

我试过:

  // this fires when I click parent button, 
  // but it also fires when I click the child button << problem
  $("#parentDiv").on("show.bs.collapse", () => {
      console.log("parent");
    });

  // this never fires << problem
  $("#childDiv").on("show.bs.collapse", () => {
      console.log("child");
    });

网址

<button data-toggle="collapse" data-target="#parentDiv" aria-controls="parentDiv"
        aria-expanded="false" aria-label="Toggle parent">Show parent
</button>

<div class="collapse" id="parentDiv">
  <p>This is the parent</p>

  <button data-toggle="collapse" data-target="#childDiv" aria-controls="childDiv" 
          aria-expanded="false" aria-label="Toggle child">Show child
  </button>

  <div class="collapse" id="childDiv">
    <p>This is the child</p>
  </div>
</div>

我最终使用了什么以及为什么。

我首先尝试使用接受的答案,因为这就是它应该如何完成的,糟糕的是,当我更改路线时 jQuery 无法正常工作,它会中断。

我最终使用了某种看起来像是可能重复的公认答案的代码,因为这似乎是让 jQuery 可靠工作的唯一方法。

$(document).ready(() => {
   $("#parentDiv").on("show.bs.collapse", (e) => {
     if (e.target.id == "childDiv") {
       //enter code here
     }
   })
}); 

为了防止父事件监听器在点击子级时执行,只需添加 event.stopPropagation 以防止事件冒泡。

 // this fires when I click parent button, $("#parentDiv").on("show.bs.collapse", () => { console.log("parent"); }); // this fires on click of child button $("#childDiv").on("show.bs.collapse", (e) => { //prevent event bubbling up to parent listener e.stopPropagation(); console.log("child"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.js"></script> <button data-toggle="collapse" data-target="#parentDiv" aria-controls="parentDiv" aria-expanded="false" aria-label="Toggle parent">Show parent </button> <div class="collapse" id="parentDiv"> <p>This is the parent</p> <button data-toggle="collapse" data-target="#childDiv" aria-controls="childDiv" aria-expanded="false" aria-label="Toggle child">Show child </button> <div class="collapse" id="childDiv"> <p>This is the child</p> </div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM