[英]jQuery.cookie : no update of the cookie despite a very simple code
I just have a menu withe blocks which can be hidden.我只有一个可以隐藏的带有块的菜单。 In order to memorize their state during the visit, I decided to use jQuery.cookie() My code is very basic:
为了在访问过程中记住他们的 state,我决定使用 jQuery.cookie() 我的代码很基础:
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))
});
});
" As not excepted, the cookie values never change: the show/hide works, if I change "if ( valeur_id == true)" by "if (valeur_id)", the cookies change but only once " 不例外,cookie 值永远不会改变:显示/隐藏有效,如果我将 "if (valeur_id == true)" 更改为 "if (valeur_id)",则 cookies 更改但只有一次
I'm so desperate!我好绝望! this should be easyyy !
这应该很容易!
thx for reading this !感谢阅读!
If you are using this "plugin"如果您正在使用此“插件”
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
Your problem is that you are writing a boolean to your cookie, which is translated to a string on write to the cookie.您的问题是您正在将 boolean 写入您的 cookie,它在写入 cookie 时被转换为字符串。 Reading back from the cookie does not translate in reverse.
从 cookie 中读取不会反向翻译。 So no matter whether you put
true
or false
in the cookie, your check for因此,无论您在 cookie 中输入
true
还是false
,您的检查
if ( valeur_id == true)
always evaluates to boolean true.始终评估为 boolean 为真。 This is because
"true"
and "false"
are both strings which evaluate to "truthy" in such a check.这是因为
"true"
和"false"
都是在这种检查中评估为 "truthy" 的字符串。
If you want to stick with that library, you should write strings to the cookie and expect strings on read.如果您想坚持使用该库,您应该将字符串写入 cookie 并期望读取字符串。
$.cookie( 'cookieName', 'true' );
And:和:
if ( $.cookie( 'cookieName' ) === 'true' )
Important note:重要的提示:
As an aside, if you run the entire code sample on your page, you'll never see the result of the clicking on read of the cookie when you reload the page.顺便说一句,如果您在页面上运行整个代码示例,那么当您重新加载页面时,您将永远不会看到单击读取 cookie 的结果。 Your first block of code overwrites whatever was set by clicks on previous page loads.
您的第一个代码块会覆盖通过单击上一页加载设置的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.