2015-06-04 43 views
2

我翻阅了一些较旧的问题,并了解到要解决此问题,我需要实现cookie并以某种方式记住状态。作为jquery的新手,对我来说实现这一点有点棘手。刷新时jQuery切换状态发生变化

这里是我的javascript代码:

$(document).ready(function(){ 

$('.trthJobStatus caption').click(function() { 
    $('.trthJobStatus th,.trthJobStatus td').slideToggle('1000'); 

}); 
}); 

任何人都知道我该如何使用cookies记住状态,避免我的切换状态改变刷新页面时?

在此先感谢!

+1

看一看在此,http://stackoverflow.com/questions/7934139/jquery-slidetoggle-keep-open-until-closed,同样的问题,这已经回答了。可能的重复 –

+0

@loganSarav - 尝试了解决方案,但没有工作:( –

回答

2

我非常喜欢使用localStorage over cookies,特别是如果你有一个需要与设备无关的应用程序。请注意,下面的代码在不再需要时不会重置localStorage变量。

$(document).ready(function(){ 

     if(localStorage['trthJobStatus']){ 
     $('.trthJobStatus th,.trthJobStatus td').slideToggle('1000'); 
     } 
     $('.trthJobStatus caption').click(function() { 
     localStorage['trthJobStatus'] = true; 
     $('.trthJobStatus th,.trthJobStatus td').slideToggle('1000'); 
     }); 
    }); 

编辑:这是工作的解决方案!

$(document).ready(function(){ 
if(window.localStorage.getItem('trthJobStatus') === 'true'){ 
    $('.trthJobStatus th,.trthJobStatus td').slideUp('1000'); } 
    $('.trthJobStatus caption').click(function(){ 
    if(window.localStorage.getItem('trthJobStatus') === 'true'){ window.localStorage.setItem('trthJobStatus', 'false');             }else{ 
     window.localStorage.setItem('trthJobStatus', 'true'); 
     } 
     console.log(window.localStorage.getItem('trthJobStatus')); 
    $('.trthJobStatus th,.trthJobStatus td').slideToggle('1000'); }); 

}); 
+0

我试过了代码,但现在表格根本没有切换 –

+0

是的,当然,我很抱歉,我们必须检查localStorage ['trthJobStatus'] = localStorage ['trthJobStatus']?false:true;' –

+0

尝试了这个并仍然不起作用: 'if(localStorage [ 'trthJobStatus']){ \t \t $()的slideToggle( '1000 ') 'trthJobStatus日.trthJobStatus TD。';} $()点击(函数(' trthJobStatus字幕。'){ \t \t localStorage ['trthJobStatus'] = localStorage ['trthJobS tatus']? false:true ;; $('。trthJobStatus th,.trthJobStatus td')。slideToggle('1000'); });' –