[英]Why isn't my cookie updating?
I am making a dark mode for a site using a button toggle. 我正在使用按钮切换为网站设置暗模式。 To keep the dark mode saved when changing pages, I am using cookies.
为了在更改页面时保持暗模式保存,我正在使用cookie。 When pressing the toggle again, the dark mode is disabled but is not saving and I am not sure why.
再次按下切换开关时,黑暗模式将被禁用,但无法保存,我不确定为什么。
Ps. PS。 I am new at javascript so this may be a dumb mistake.
我是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');
});
}
When you press the toggle button you also want to toggle the True/False value of the cookie. 当您按下切换按钮时,您还想切换cookie的True / False值。 Now you always either set it to True or to False depending on the first state.
现在,根据第一个状态,您始终可以将其设置为True或False。
Use ! $.cookie('darkModeOn')
使用
! $.cookie('darkModeOn')
! $.cookie('darkModeOn')
as value to store into the cookie to automatically toggle the boolean value. ! $.cookie('darkModeOn')
作为值存储在cookie中,以自动切换布尔值。
EDIT 编辑
It was indeed not working, and I found out that it was not working because of the boolean values. 它确实不起作用,我发现由于布尔值,它不起作用。 The boolean values are stored as string (
"false"
and "true"
) since if ( "false")
gives boolean true, the if is always executed. 布尔值存储为字符串(
"false"
和"true"
),因为if ( "false")
为布尔值true,则始终执行if。 When you use integers instead of booleans this would work, but you can also change the if to: 当您使用整数而不是布尔值时,这将起作用,但是您也可以将if更改为:
if ($.cookie('darkModeOn')=="true") //...
If you use integers it also works: 如果使用整数,它也可以工作:
https://jsfiddle.net/6m2ydrh2/12/ 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');
}
See also this post: jquery cookie set value to boolean true . 另请参阅此帖子: jquery cookie将value设置为boolean true 。 The boolean values are stored as string and therefor causing problems.
布尔值存储为字符串,因此会引起问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.