如何使我的导航项再次处于非活动状态?

How do I make my navigation item inactive again?

我的导航栏有问题。我正在尝试创建一项功能,当我单击一个导航项时,它会展开其子项。这非常有效。当我点击另一个导航项目时,它会折叠前一个项目并展开当前项目。这也很完美。我最近添加了一个新功能,如果你们明白我的意思,我希望当前导航项保持其悬停状态,使其显示为活动状态。

我能想到的就是这段代码,它确实做了一些我想要的,但它不会在单击当前导航项后使导航项再次处于非活动状态,只有在我单击新导航项时才会如此。如果有任何不清楚的地方,我会提供 link.

$(function(){
    $(".main-nav").on("click",function(){
        $(this).siblings().find(".inner-nav").hide(); //collapse siblings
        $(this).siblings().find('a').attr('id', ''); //make siblings inactive

        $(this).find(".inner-nav").toggle(); //expand current item
        $(this).find("a").attr('id','nav-active'); //make current item active
        $(this).find("ul").find("a").attr('id',''); //remove the nav-active ID from the current items children, as it also will appear as active, which is not the desired functionality
    });
});

我真的不能很好地理解你的意思,但让我猜猜.. 当你点击任何一个 children 时,它会崩溃整个 div .. 在这种情况下你需要 e.stopPropagation();

$(function(){
    $(".main-nav").on("click",function(){
        $(".inner-nav").not($(this).find(".inner-nav")).hide();
        $(this).find(".inner-nav").toggle();
    });
    $(".main-nav > ul > li > a").on('click' , function(e){
        e.stopPropagation();
      $(".main-nav > ul > li > a").not($(this)).attr('id' , '');
      $(this).attr('id' , 'nav-active');
    });
});

希望这就是您要找的

Working Demo

试试这个:

$(function(){
    $(".main-nav").on("click",function(){
        $(this).siblings().find(".inner-nav").hide();
        $(this).siblings().find('a').attr('id', '');

        $(this).find(".inner-nav").toggle();
        //$(this).find("a").attr('id','nav-active');
    if ($(this).find("a").attr('id') == 'nav-active') {
        $(this).find("a").attr('id','');
    } else {
        $(this).find("a").attr('id','nav-active');
    }
        $(this).find("ul").find("a").attr('id','');
    });
});

我添加了简单的验证:

if ($(this).find("a").attr('id') == 'nav-active') {
    $(this).find("a").attr('id','');
} else {
    $(this).find("a").attr('id','nav-active');
}

fiddle

希望,我理解你是对的。