Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 切换div并设置cookie以保存jQuery_Javascript_Jquery_Cookies - Fatal编程技术网

Javascript 切换div并设置cookie以保存jQuery

Javascript 切换div并设置cookie以保存jQuery,javascript,jquery,cookies,Javascript,Jquery,Cookies,我使用下面的代码切换一个特定的div,并用cookie保存设置,以便它保留更改 但由于某些原因,“保存cookie”部分无法正常工作。例如,使用以前的浏览器按钮时,cookie似乎没有保存 在我当前的代码中,我遗漏了什么?添加一个cookie并检查它 函数getCookieValue(a){ var b=document.cookie.match('(^;)\\s*'+a+'\\s*=\\s*([^;]+); 返回b?b.pop():“”; } $(文档).ready(函数(){ var red

我使用下面的代码切换一个特定的div,并用cookie保存设置,以便它保留更改

但由于某些原因,“保存cookie”部分无法正常工作。例如,使用以前的浏览器按钮时,cookie似乎没有保存

在我当前的代码中,我遗漏了什么?添加一个cookie并检查它

函数getCookieValue(a){ var b=document.cookie.match('(^;)\\s*'+a+'\\s*=\\s*([^;]+); 返回b?b.pop():“”; } $(文档).ready(函数(){ var redEl=$('input#togglebtw'); if(document.cookie.indexOf('togglebtw=')!=-1){ prop(“checked”、$.parseJSON(getCookieValue(“togglebtw”))); } 如果(红色道具(“选中”)){ $(“.price container.price include tax”).hide(); $(“.price container.price不含税”).show(); }否则{ $(“.price container.price不含税”).hide(); $(“.price container.price include tax”).show(); } $('input#togglebtw')。单击(函数(){ var expiryDate=新日期(); expiryDate.setDate(expiryDate.getDate()+31); expireydate=expireydate.toutString(); if($(this.attr(“类”)==“btwToggler”){ 如果(红色道具(“选中”)){ $(“.price container.price include tax”).hide(); $(“.price container.price不含税”).show(); }否则{ $(“.price container.price不含税”).hide(); $(“.price container.price include tax”).show(); } document.cookie=“togglebtw=“+this.checked.toString()+”;expires=“+expireydate; } }); });
使用本地或会话存储,那么您就不必担心cookie是否正确

试试这个简化版

const checkBTW=函数(){
常量checked=$('#togglebtw')。是(“:checked”);
$(“.price container.price include tax”).toggle(!选中);
$(“.price container.price unclused tax”).toggle(选中);
setItem(“togglebtw”,选中?“true”:“false”);
};
$(函数(){
$(“#togglebtw”)
。打开(“单击”,勾选BTW)
.prop(“选中”,localStorage.getItem(“togglebtw”)=“true”);
检查BTW();
});

如果您不需要服务器上的cookie,那么逻辑选择是localStorage(跨会话)或sessionStorage(在同一会话中)。如果您确实需要服务器上的cookie,那么请使用,始终依靠数千名测试人员为您完成这项工作。要找出代码的错误,调试的第一个顺序是
console.log
所有操作,以确保变量和返回值是您期望的值。@mplungjan cookie不需要存储在服务器上,因此它也可以是本地cookie。你能帮我一下吗,我应该做些什么代码更改来改变这个吗?非常感谢!作品完美:)