我只有一个带有可以隐藏的 block 的菜单。为了记住他们在访问期间的状态,我决定使用 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))
});
});
” 不异常(exception),cookie 值永远不会改变:显示/隐藏有效,如果我将“if (valeur_id == true)”更改为“if (valeur_id)”,cookie 只会更改一次
我好绝望啊!这应该很容易!
感谢您阅读本文!
最佳答案
如果您正在使用这个“插件”
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
您的问题是您正在向 cookie 写入一个 bool 值,该 bool 值在写入 cookie 时会被转换为字符串。从 cookie 读回不会反向翻译。因此,无论您在 cookie 中输入 true
还是 false
,您都会检查
if ( valeur_id == true)
始终评估为 bool 值 true。这是因为 "true"
和 "false"
都是在此类检查中计算结果为“truthy”的字符串。
如果您想坚持使用该库,您应该将字符串写入 cookie 并期望读取字符串。
$.cookie( 'cookieName', 'true' );
还有:
if ( $.cookie( 'cookieName' ) === 'true' )
重要说明:
顺便说一句,如果您在页面上运行整个代码示例,则在重新加载页面时您将永远看不到单击读取 cookie 的结果。您的第一个代码块将覆盖通过单击上一个页面加载而设置的任何内容。
关于javascript - jQuery.cookie : no update of the cookie despite a very simple code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7014605/