Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - Add active class to menu item when page was not in URL

I have a web application build with ASP.NET webform that uses Javascript to make the selected item active in the menu.

To obtain this result, the system compares the URL visited and the one present in the URL of the selected menu. If they match, the ACTIVE class is added.

// activate the menu in left side bar based on url
    $("#side-menu a").each(function () {
        var pageUrl = window.location.href.split(/[?#]/)[0];
        if (this.href == pageUrl) {
            $(this).addClass("active");
            $(this).parent().addClass("active"); // add active to li of the current link
            $(this).parent().parent().addClass("in");
            $(this).parent().parent().prev().addClass("active"); // add active class to an anchor
            $(this).parent().parent().parent().addClass("active");
            $(this).parent().parent().parent().parent().addClass("in"); // add active to li of the current link
            $(this).parent().parent().parent().parent().parent().addClass("active");
        }
    });

My problem is that the visited page is not always present in the menu. For example: I have a page (Product list) in the menu. When selected this item ACTIVE class was added.

If I need more details on a product, I click on the list to view the page with the details. This page was not in menu so no menu item was active.

How can I solve?

Is there a way to leave the previous active menu item selected?

question from:https://stackoverflow.com/questions/65901068/add-active-class-to-menu-item-when-page-was-not-in-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...