简体   繁体   中英

When toggling a class on a menu element. How can I make it so that class gets removed on previously toggled elements?

I have this menu with different submenu's which are just <ul> . When clicking on a submenu the.active class will get toggled and the submenu will display. However when I click on a different submenu the desired behaviour is that the.active class will be removed from the previous submenu and applied to the new one. However what obviously happens now is that the new submenu will also get the.active class and both menu's will be open at the same time which is not what I'm after.

What would be a simple way to make sure the.active class gets removed when I click the next menu item?

This is my current code

$(".menu nav ul li > ul.subnav li").on("click", function (_event) {
  $(this).children("ul.subnav").toggleClass("active");
});

Remove.active from the other active elements and add it for this element.

$(".menu nav ul li > ul.subnav li").on("click", function (_event) {
  $(".menu nav ul li > ul.subnav li ul.subnav.active").removeClass("active");
  $(this).children("ul.subnav").addClass("active");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM