简体   繁体   中英

Set parent menu item and child sub menu item to active based on URL using jQuery

I have some code I'm using for a side navigation menu that works in the main how I require.

There are two sidebar menus one on each side of a three column layout. The sidebar to the right hierarchically is the main menu and resides in an ASP.NET MasterPage. This menu sets its menu item to active (CSS) based on the URL.

The sidebar to the left is a sub menu which resides in an ASP.NET NestedMasterPage this also sets its menu item to active.

So the parent nav and the child nav should both be in an active state at the same time. However when I select a parent menu item which has a child menu item on the left only one menu state (at present the child) is active.

I know this has something to do with the URL but I'm not sure how to solve the issue.

$(document).ready(function () {
    var str = location.href.toLowerCase();

    $("#menu1 li a").each(function () {
        if (str.indexOf(this.href.toLowerCase()) > -1) {


            $("li.active").removeClass("active");

            $(this).parent().addClass("active");

        }

    });


    $("#menu2 li a").each(function () {
        if (str.indexOf(this.href.toLowerCase()) > -1) {

            $("li.active").removeClass("active");

            $(this).parent().addClass("active");

        }

    });
});

尝试使用parentUntil('topmenu')

$(this).parentsUntil('topmenu').addClass("active");

Try this:

$(document).ready(function () {
    var str = location.href.toLowerCase();

    $("#menu1 li a").each(function () {
        if (str.indexOf(this.href.toLowerCase()) > -1) {


            $("#menu1 li.active").removeClass("active");

            $(this).parent().addClass("active");

        }

    });


    $("#menu2 li a").each(function () {
        if (str.indexOf(this.href.toLowerCase()) > -1) {

            $("#menu2 li.active").removeClass("active");

            $(this).parent().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