我有这个代码来控制菜单。 我想点击打开另一个子菜单时关闭一个子菜单。
;(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);
那么在点击另一个子菜单时如何关闭一个子菜单?
答案 0 :(得分:0)
以这种方式构造func
方法应该可以解决问题:
nav-click
首先,我们以除当前单击之外的所有子导航元素为目标,并强制将其关闭,然后在当前元素上进行切换。
只需提一下:您可以使用纯js更轻松地实现此目标,或者使用任何双向数据绑定框架来实现超快速,jquery在这里无济于事,但这是您的选择。