我有这段代码来控制菜单。 我想在单击打开另一个子菜单时关闭一个子菜单。
;(function($) {
// DOM ready
$(function() {
// Add some classes and Append the mobile icon nav
$('.nav').append($('<div class="nav-mobile"></div>'));
$('.nav > ul').addClass('nav-list');
$('.nav > ul > li').addClass('nav-item');
$('.nav > ul > li > ul').addClass('nav-submenu');
$('.nav > ul > li > ul > li').addClass('nav-submenu-item');
// Add a <span> to every .nav-item that has a <ul> inside. And add an sub menu icon indicator.
$('.nav-item').has('ul').prepend('<span class="nav-click"><i></i></span>');
// Click to reveal the mobile menu
$('.nav-mobile').click(function() {
$('.nav-list').toggle();
$('.nav-submenu').hide(); // This will close the submenu when i click the top ribbon (.nav-mobile) to close the mobile menu
if (!$('.nav-list').is(':visible')) { // the menu was closed because it's not visible anymore
$('.nav-item .nav-click').each(function() { // loop through nav clicks
if ($(this).hasClass('icon-close')) { // This will toggle back the + icon on mobile menu close/open
$(this).toggleClass('icon-close');
}
});
}
});
// Dynamic binding to on 'click' and Toggle the nested nav
$('.nav-list').on('click', '.nav-click', function() {
$(this).siblings('.nav-submenu').toggle();
// This will toggle the + and - when clicked
$(this).removeClass('nav-click');
$(this).toggleClass('icon-close');
$(this).toggleClass('nav-click');
});
// This will toggle the menu/submenu/- when click outside of the menu
$('.wrapper').click(function(event) {
$('html').one('click', function() {
$('.nav-list').hide();
$('.nav-submenu').hide(); // This will close the submenu when you click the top ribbon (hamburger button) to close the mobile menu
if (!$('.nav-list').is(':visible')) { // the menu was closed because it's not visible anymore
$('.nav-item .nav-click').each(function() { // loop through nav clicks
if ($(this).hasClass('icon-close')) { // This will toggle the +/- icon on mobile menu close/open
$(this).toggleClass('icon-close');
}
});
}
});
event.stopPropagation();
});
});
})(jQuery);
那么如何在点击另一个子菜单时关闭一个子菜单呢?
最佳答案
以这种方式构造 nav-click
方法应该可以解决问题:
// Dynamic binding to on 'click' and Toggle the nested nav
$('.nav-list').on('click', '.nav-click', function(){
$('.nav-submenu').not($(this).siblings('.nav-submenu')).hide();
$('.nav-item .nav-click').not(this).removeClass('icon-close');
$(this).siblings('.nav-submenu').toggle();
$(this).toggleClass('icon-close');
});
首先,我们定位所有子导航元素,不包括当前单击的元素并强制关闭它,然后对当前元素进行切换。
只需提及:您可以使用纯 js 更轻松地实现此目的,或者使用任何双向数据绑定(bind)框架实现超快速,jquery 在这里没有帮助,但这是您的选择。
关于javascript - 单击另一个子菜单时如何关闭一个子菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293740/