简体   繁体   中英

Active links don't show the class name added when the page is refreshed or when the same link is clicked from another page

Script:

$(".classname li a").each(function() {
    var hreflink = $(this).attr("href");
    if (hreflink == location.href) {
        $(this).addClass("active");
    } else {
        $(this).removeClass("active");
    }
});

CSS:

.classname li a.active{color:#ef9223;}

Whenever I do a page refresh, if the same link is on a different page, the active class is no longer applied to that link.

Actual exmple i have the following Navigation links ABCDEFGH .... Z. And the same Navigation is in the main page(header section).. so when i click on any one link .. it needs to be active on when i arrive to any one ABCD E..or Z pages. And even on page refresh it needs to retain the active link. Hope that explains...and helps :)

Any help, inputs, solution would be much appreciated.

A class, or anything that you add with JavaScript does not persist on page refresh. That's just how it works.

JavaScript is only modifying your locally loaded HTML elements and structure. Once you refresh the page, or go to another page, all of that state is cleared out by the incoming page load. The server has no knowledge of anything you did on that page. It will send a new page with the default state, and any JavaScript will then run. This script also has no knowledge of any previous page loads or script execution.

If you want state to persist across page loads, you need to do it at the server side, which involves making AJAX calls to the server to let it know what links you want to be "active", and then the server would be responsible for adding that class on subsequent page loads.

Inside of your each loop, this is actually the anchor tag not the tag that has the class 'classname'. Your css should be:

.active {color:#ef9223;}

Also, you do not need the remove class if this code is being run on page load.

CHeck out this jsFiddle for an example - http://jsfiddle.net/XWLWL/7/

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