[英]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.