javascript - 刷新时 jQuery 切换状态发生变化

标签 javascript jquery cookies

我浏览了一些较旧的问题,发现要解决这个问题,我需要实现 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/

相关文章:

php - 使用 session ID 访问 session 数据

python - 如何避免每次使用 Selenium 和 Python 时都出现 Instagram 登录页面

javascript - AngularJS ng-pattern 的正则表达式问题

Javascript:parseFloat 不工作

jquery - Rails 和 Ajax/异步加载部分

javascript - 在 SlickGrid 中保存更改

javascript - 如何设置 cookie 来记住打开的选项卡?选项卡是使用 Coldfusion 和 Javascript 创建的

javascript - 什么时候使用 process.nextTick 最好?

javascript - Handlebars.js #each 不工作

javascript - 内容不会显示在 jQuery 的切换按钮上