2013-05-05 65 views
0

我正在一个网站上工作,并希望在localStorage中存储一个类,虽然我遇到了一些问题。addClass - 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记住哪个元素具有类current

这是我迄今为止写到的localStorage,但我认为它不对。 (我正在使用Modernizr)。

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

此外,有没有办法测试localStorage是否工作?

回答

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

演示JShttp://jsfiddle.net/5vmBe/3/

希望这会帮助你。

+0

这有助于非常感谢!如果元素具有'.current',但是如何更改值?它会像'if($('#2')。hasClass('current')){$('body')。append('

yay!
');'}? – user2352358 2013-05-05 19:42:07

+0

我没有明白。你想改变本地存储的价值吗?在这种情况下,只能点击'li'元素才能更改该值。 – moustacheman 2013-05-06 06:00:02

+0

这很好,我解决了。谢谢 :) – user2352358 2013-05-06 20:49:22