为什么不是't我的cookie更新

Why isn't my cookie updating?

本文关键字:我的 cookie 更新 为什么不      更新时间:2023-09-26

我正在使用按钮切换为网站创建一个黑暗模式。为了在更改页面时保存黑暗模式,我使用了Cookie。再次按下开关时,暗模式被禁用,但没有保存,我不知道为什么。

Ps。我是javascript新手,所以这可能是一个愚蠢的错误。

if ($.cookie('darkModeOn')){
      $('html').toggleClass('dark-mode');
      $('#dark-toggle').click(function(){
      $.cookie('darkModeOn', false, { expires: 7 });
      $('html').toggleClass('dark-mode');
      });
   }
   else
   {
      $('#dark-toggle').click(function(){
      $.cookie('darkModeOn', true, { expires: 7 });
      $('html').toggleClass('dark-mode');
      });
    }

当您按下切换按钮时,您还希望切换cookie的True/False值。现在,您总是根据第一种状态将其设置为True或False。

使用! $.cookie('darkModeOn')作为值存储到cookie中,以自动切换布尔值。


编辑

它确实不起作用,我发现它不起作用是因为布尔值。布尔值存储为字符串("false""true"),因为if ( "false")给出布尔值true,所以总是执行if。当您使用整数而不是布尔值时,这将起作用,但您也可以将if更改为:

if ($.cookie('darkModeOn')=="true") //...

如果你使用整数,它也可以:

https://jsfiddle.net/6m2ydrh2/12/

$('#dark-toggle').click(function(){
       //this gets executed each click so we need to toggle the boolean value.
      if ($.cookie('darkModeOn')==0){
          $.cookie('darkModeOn', 1, { expires: 7 });
      }else{
          $.cookie('darkModeOn', 0, { expires: 7 });
      }
      console.log( "cookie:"+$.cookie('darkModeOn')) ;
      $('#test').toggleClass('dark-mode');
  });
  if ($.cookie('darkModeOn')){
       //this is only executed on load
      $('#test').toggleClass('dark-mode');
  }

另请参阅本文:jquerycookie将值设置为布尔值true。布尔值存储为字符串,因此会引起问题。