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
872 views
in Technique[技术] by (71.8m points)

javascript - How to keep active class when changing pages

I am trying to add an active class to nav item, depending what page your on. I am using this script:

<script type="text/javascript">
    $(document).ready(function () {
        $("#side-bar a").click(function () {
            var id = $(this);

            $(id).siblings().find(".active").removeClass("active");
            $(id).addClass("active");
            localStorage.setItem("selectedolditem", id);
        });

        var selectedolditem = localStorage.getItem('selectedolditem');

        if (selectedolditem !== null) {
            $(selectedolditem).siblings().find(".active").removeClass("active");
            $(selectedolditem).addClass("active");
        }
    });
</script>

See full jsfiddle here: https://jsfiddle.net/ebo7hLo9/ It adds the active class, but it loads a new page, it disappears. What am I doing wrong?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

https://jsfiddle.net/ebo7hLo9/10/ - here's a fiddle!

$(document).ready(function () {

            $("#side-bar a").click(function () {
                var id = $(this);

                $(".active").removeClass("active");
                $(id).addClass("active");
                localStorage.setItem("selectedolditem", $(id).text());

            });

            var selectedolditem = localStorage.getItem('selectedolditem');

            if (selectedolditem !== null) {

                $("a:contains('" + selectedolditem + "')").addClass("active");
            }
        });

Your code was having issues remembering what element to grab. I think it's due to the web storage API's unfamiliarity with objects. Instead I got the text from the element that was selected, stored it in localStorage and on page load matched it with the correct element. Also there was part of your code that was dealing with finding the class "active" within the siblings() of the selected element and removing it. That complex of code is largely unnecessary. I replaced it with the class selector $(".active")

I didn't change this in the code, but I'd advise against using localStorage in favor of sessionStorage so that the storage will clear itself on tab/browser close.

For more info take a look at this previous stackoverflow post: Storing Objects in HTML5 localStorage


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

...