【问题标题】:How to use local storage for active class?如何将本地存储用于活动课程?
【发布时间】:2013-12-15 15:07:42
【问题描述】:

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

菜单-

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

我尝试过使用本地存储-

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

现在这对我没有帮助。

如何在本地存储中存储活动类?刷新页面时,我失去了这个活动课程。 这个问题被问了很多次,但我没有得到任何简单的方法。

【问题讨论】:

  • 这不是有效的语法:var menuactive= localStorage.setItem('mySelectValue', $(this).addClass('active');

标签: javascript jquery local-storage


【解决方案1】:

您似乎想记住哪个元素(上次,刷新前)具有“活动”类。

因此,如果您有已知数量的列表项,您可以只跟踪索引并存储它。

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

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

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

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

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

【讨论】:

  • 是 isNaN 不是 isNan ,你会得到 isNan 没有定义
【解决方案2】:

您必须编写代码以将活动类持久保存在本地存储中并从本地存储中检索活动类。

localStorage.setItem('ActiveClass', ClassName);

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

如果您使用的是 KnockoutJS http://knockoutjs.com/,那么您可以将部分视图模型保存在本地存储中。这个问题讨论了这个。

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

希望对您有所帮助。

【讨论】:

    【解决方案3】:

    $(this).addClass('active') 将返回 $(this),这是单击的 li 的 jquery 版本,每次重新加载时都会更改。

    你需要存储的是一个绝对引用,比如被点击的li的索引:

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

    【讨论】:

      猜你喜欢
      • 2022-10-02
      • 2021-01-04
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多