addClass - LocalStorage问题

时间:2013-05-05 16:59:53

标签: javascript jquery local-storage modernizr

我正在开发一个网站,并希望在localStorage中存储一个类,尽管我遇到了一些问题。

这是HTML:

<ul class="type">
  <li id="1" class="current">Example 1</li>
  <li id="2">Example 2</li>
</ul>

我有一些jQuery在点击时为其中一个示例添加了一个类。

当课程current处于活动状态时,它会更改网站上的某些值。基本上,当您访问该网站时,#1已经有了current类,但如果我添加了#2类,我希望localStorage能够记住哪个元素具有该类{ {1}}。

这是我到目前为止所写的current,但我认为这不对。 (P.S.我正在使用Modernizr)。

localStorage

另外,有没有办法测试function temp_type(){ var type = $('.type li').hasClass('current'); } $('#1').click(function() { $('#2').removeClass('current'); $(this).addClass('current'); if(Modernizr.localstorage) localStorage.setItem('temp_type'), $('.type li').hasClass('current'); }); $('#2').click(function() { $('#1').removeClass('current'); $(this).addClass('current'); if(Modernizr.localstorage) localStorage.setItem('temp_type'), $('.type li').hasClass('current'); }); if(Modernizr.localstorage){ var type = localStorage.getItem('temp_type'); if(type){ $('.type li').hasClass('current'); temp_type(); } } 是否有效?

1 个答案:

答案 0 :(得分:0)

这可以用简单的方式编写,试试下面的

<强> HTML

<ul class="type">
  <li id="1">Example 1</li>
  <li id="2">Example 2</li>
</ul>
<br />
<a href="javascript:void(0);">Check Storage</a>

<强>脚本

$(document).ready(function(){
    $('.type li').on('click', function(event){
        $('.type li').removeClass('current');
        $(this).addClass('current');
        if(Modernizr.localstorage){
            window.localStorage['temp_type'] = $(this).attr('id'); /*Storing the id of the selected element*/
        }
    });

    $('a').on('click', function(event){ 
        alert(window.localStorage['temp_type']); /*Check the current storage*/
    });
});

<强> CSS

li.current {
    color: red;
}

演示JS http://jsfiddle.net/5vmBe/3/

希望这会对你有所帮助。