简体   繁体   中英

remove active class from sub menu item when other item is clicked

Hi here is my fiddle:

$(function(){

    $('#nav li').on('click', function(){

        $(this).addClass('active').siblings().removeClass('active');
        $(this).find('.sub-menu').addClass('showMenu');

    });
    $('ul#nav > li').hover(function(){
        if ($(this).children('ul').length > 0){    
             $(this).find('.sub-menu').addClass('showMenu');
        }
    }, function(){ 
             $(this).find('.sub-menu').removeClass('showMenu');
    });

how you see in fiddle when you click on each main li item active class is ok, but when you try to click on one of sub menu item it stays active even if I am clicking on other li item.

$(function() {
$('#nav li').on('click', function() {
    $('#nav').find('.active').removeClass('active'); // remove active class in all #nav elements [added]
    $(this).addClass('active');
    $(this).find('.sub-menu').addClass('showMenu');

});
$('ul#nav > li').hover(function(){
    if ($(this).children('ul').length > 0){    
         $(this).find('.sub-menu').addClass('showMenu');
    }
}, function(){ 
         $(this).find('.sub-menu').removeClass('showMenu');
});
$(function(){

    $('#nav li').on('click', function(){

        $(this).addClass('active').siblings().removeClass('active');
        $(this).siblings().find('li').removeClass('active');//added
        $(this).find('.sub-menu').addClass('showMenu');

    });
    $('ul#nav > li').hover(function(){
        if ($(this).children('ul').length > 0){    
             $(this).find('.sub-menu').addClass('showMenu');
        }
    }, function(){ 
             $(this).find('.sub-menu').removeClass('showMenu');
    });

});

http://jsfiddle.net/Hnk9W/26/

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