Javascript cookie:尽管代码非常简单,但没有更新cookie
我只有一个可以隐藏的带E块的菜单。为了记住他们在访问期间的状态,我决定使用jQuery.cookie() 我的代码非常基本:Javascript cookie:尽管代码非常简单,但没有更新cookie,javascript,jquery,cookies,Javascript,Jquery,Cookies,我只有一个可以隐藏的带E块的菜单。为了记住他们在访问期间的状态,我决定使用jQuery.cookie() 我的代码非常基本: jQuery(document).ready(function(){ $(".titre_acordeon").next().hide(); $(".titre_acordeon").each(function () { jQuery.cookie($(this).parent().attr("id"),false, {path: "/"}
jQuery(document).ready(function(){
$(".titre_acordeon").next().hide();
$(".titre_acordeon").each(function () {
jQuery.cookie($(this).parent().attr("id"),false, {path: "/"});
});
$(".titre_acordeon_0").next().show();
$(".titre_acordeon_0").each(function () {
jQuery.cookie($(this).parent().attr("id"),true, {path: "/"});
});
});
jQuery(document).ready(function(){
$(".titre_acordeon, .titre_acordeon_0").click(function() {
$(this).next().toggle("medium");
var id = $(this).parent().attr("id");
var valeur_id = jQuery.cookie(id);
alert(valeur_id)
if ( valeur_id == true)
{
jQuery.cookie(id, false, {path: "/"});
}
else if ( valeur_id == false)
{
jQuery.cookie(id, true, {path: "/"});
}
alert(jQuery.cookie(id))
});
});
"
不例外,cookie值从不更改:显示/隐藏有效,如果我将“if(valeur_id==true)”更改为“if(valeur_id)”,cookie只更改一次
我太绝望了!这应该很容易
谢谢阅读!如果您正在使用此“插件”
您的问题是,您正在向cookie写入布尔值,在写入cookie时会将其转换为字符串。从cookie读回不会进行反向转换。因此,无论您在cookie中输入的是true
还是false
,检查
if ( valeur_id == true)
始终计算为布尔值true。这是因为在这种检查中,“true”
和“false”
都是计算为“truthy”的字符串
如果您想继续使用该库,您应该将字符串写入cookie,并在读取时使用字符串
$.cookie( 'cookieName', 'true' );
以及:
重要提示:
另一方面,如果您在页面上运行整个代码示例,则在重新加载页面时,您将永远看不到单击读取cookie的结果。您的第一个代码块将覆盖以前页面加载时单击设置的内容。oops我忘了说警报(valeur_id)和警报(jQuery.cookie(id))始终返回相同的false或true,具体取决于初始值Yep我知道它将覆盖^^^其初始值…我在js中是新手-不在开发中-因此thx强调了我的错误!没问题-关于使用字符串的建议解决了你的问题吗?sry我没有注意到你的最后一篇帖子:是的,thx再次出现问题
if ( $.cookie( 'cookieName' ) === 'true' )