![](/img/trans.png)
[英]How to prevent bootstrap dropdown submenu click closing the parent dropdown
[英]Bootstrap dropdown submenu closing upstream submenu
我有一個兩個級別的下拉菜單,效果很好,但是當我添加另一個級別時,JS似乎正在從上一個子菜單中刪除open
類,這意味着無法看到所需的第三級菜單,即使它確實添加了open
類。
我已經找到了這個JS:
$(function() {
$('li.dropdown-submenu').on('click', function(event) {
event.stopPropagation();
if ($(this).hasClass('open')){
$(this).removeClass('open');
} else {
$('li.dropdown-submenu').removeClass('open');
$(this).addClass('open');
}
});
});
我認為這是不希望地關閉了上一個子菜單。 HTML與此示例非常相似。
使用該示例中的JS改編版,我得到了第三級,但是任何給定的打開子菜單在單擊另一個子菜單時都不會自動關閉。
$(document).ready(function(){
$('.dropdown-submenu a').on("click", function(e){
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
});
在這里需要最好的兩者!
我想您幾乎已經擁有了,您只需要尋找不同的點擊即可。
下面我采取的方法是處理所有a
點擊,但然后檢查它是否有一個類的test
,然后按照您的代碼逐字否則,如果它沒有一個類的test
它,然后隱藏所有的子菜單,去為其默認href。
<script>
$(document).ready(function(){
$('.dropdown-submenu a').on("click", function(e){
if ($(this).hasClass('test')) {
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
} else {
$('.dropdown-submenu ul').hide();
}
});
});
</script>
您更新的工作示例: https : //www.w3schools.com/code/tryit.asp?filename=FUB7ECWP20DA
也許這就是您要尋找的。
單擊另一個子菜單時,此代碼關閉子菜單。
使用Javascript
$(document).ready(function(){
$('.dropdown-submenu a.test').on("click", function(e){
/* This is to hide all dropdown-menu children if the parent(dropdown-submenu) in the element have been clicked */
$(this).next('ul').find('.dropdown-menu').each(function(){
$(this).hide();
});
/* This is to find another dropdown-menu have has been opened and hide its submenu */
var xw = $(this);
$(this).closest(".dropdown-menu").find('.dropdown-submenu a.test').not(xw).each(function(){
if($(this).next("ul").is(":visible")){
$(this).next("ul").hide();
}
});
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
});
和JSFiddle示例: https ://jsfiddle.net/synz/vasho634/
我希望這就是你想要的。 這是解決方案,不是完全證明,但要達到您想要的程度
$(document).ready(function(){
$('.dropdown-submenu a.test').on("click", function(e){
siblingUl = $(this).parent().siblings("li.dropdown-submenu").children("ul").css("display");
if(siblingUl == "block"){
$(this).parent().siblings("li.dropdown-submenu").children("ul").toggle();
}
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.