我浏览了一些较旧的问题,发现要解决这个问题,我需要实现 cookie 并以某种方式记住状态。作为 jquery 的新手,我发现实现这个有点棘手。
这是我的 JavaScript 代码:
$(document).ready(function(){
$('.trthJobStatus caption').click(function() {
$('.trthJobStatus th,.trthJobStatus td').slideToggle('1000');
});
});
有人知道如何使用 cookie 来记住状态并避免刷新页面时切换状态发生更改吗?
提前致谢!
最佳答案
我非常喜欢使用 localStorage 而不是 cookie,特别是如果您有一个需要与设备无关的应用程序。请注意,当不再需要 localStorage var 时,下面的代码不会重置它。
$(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'); });
});
关于javascript - 刷新时 jQuery 切换状态发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30649051/