如何使用本地存储进行活动类? [英] How to use local storage for active class?

查看:63
本文介绍了如何使用本地存储进行活动类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将所选菜单项的Cookie存储在本地存储中?

How do I keep cookie stored of selected menu item with local storage?

菜单 -

<ul class="nav nav-pills">
    <li class="active"><a href="#" >Customers</a></li>
    <li><a href="#" >Statics</a></li>
    <li><a href="#" >payroll</a></li>
</ul>

切换活动类 -

<script type="text/javascript">
    $(function () {
        $('.nav-pills li').click(function () {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
        });
    });
</script>

使用localstorage我试过 -

Using localstorage I tried-

<script type="text/javascript">
    $(function () {
        $('.nav-pills li').click(function () {
            $(this).siblings().removeClass('active');
                var menuactive = localStorage.setItem('mySelectValue', $(this).addClass('active');
                $(this).addClass(localStorage.getItem('mySelectValue'));
            });
        });
</script>

现在这对我没有帮助。

如何在本地存储中存储活动类?当刷新页面时,我会丢失此活动类。
这个问题被问过多次,但我没有得到任何简单的方法。

How do I store active class in local storage? I lose this active class when page is refreshed. This question is asked many times but I didn't get any simple way of doing it.

推荐答案

好像你想要记住哪一个element有(上次,刷新前)'active'类。

It seems like you want to remember which element had (last time, before refresh) the 'active' class.

所以如果你有一个已知数量的列表项,你可以跟踪索引和存储它。

So if you've got a known number of list items, you could just keep track of the index, and store that.

$(function () {
    $('.nav-pills li').click(function () {

        $(this).siblings().removeClass('active');
        $(this).addClass('active');

        var activeIndex = $(this).index();
        localStorage.setItem('mySelectValue', activeIndex);
    });

然后你可以有一个onload函数,就像这样...

And then you can have an onload function, something like this...

    var activeIndex = localStorage.getItem('mySelectValue');
    if (isNaN(activeIndex)) {
        console.log('nothing stored');
    } else {
        $('.nav-pills li:nth-child('+activeIndex+')').addClass('active');
    }

这篇关于如何使用本地存储进行活动类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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