如何在更改页面时保持活动类 [英] How to keep active class when changing pages

查看:66
本文介绍了如何在更改页面时保持活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个活动类添加到导航项,具体取决于您的页面。我正在使用这个脚本:

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>

在此处查看完整的jsfiddle: https://jsfiddle.net/ebo7hLo9/
它添加了活动类,但它加载了新页面,它就消失了。我做错了什么?

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

推荐答案

https://jsfiddle.net/ebo7hLo9/10/ - 这是一个小提琴!

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");
            }
        });

您的代码在记住要抓取的元素时遇到问题。我认为这是由于网络存储API不熟悉对象。相反,我从选中的元素中获取文本,将其存储在localStorage中,并在页面加载时将其与正确的元素匹配。还有一部分代码处理在所选元素的 siblings()中查找活动类并将其删除。代码复杂很大程度上是不必要的。我用类选择器替换它 $(。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")

我没有改变它代码,但我建议不要使用 localStorage 支持 sessionStorage ,以便存储将在tab /上清除浏览器关闭。

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.

有关更多信息,请查看以前的stackoverflow帖子:在HTML5 localStorage中存储对象

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

这篇关于如何在更改页面时保持活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆