2013-05-05 82 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