How to use local storage for active class?

2020-03-31 06:40发布

问题:

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

Menu-

<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>

Toggling active class-

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

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>

Now this didn't help me.

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.

回答1:

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

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


回答2:

You will have to write code to persist the active class in local storage and retrieve active class from local storage.

localStorage.setItem('ActiveClass', ClassName);

var activeClass = localStorage.getItem('ActiveClass');
$(item).addClass(activeClass);

If you were using KnockoutJS http://knockoutjs.com/ then you can persist part of your viewModel in local storage. This question discusses this.

How can I implement MVVM with offline storage and Knockout.js?

Hope that helps.



回答3:

$(this).addClass('active') will return $(this), the jquery version of the li clicked, which changes at each reload.

What you need to store is an absolute reference, like the index of the li that is clicked:

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