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