javascript - jQuery.cookie : no update of the cookie despite a very simple code

标签 javascript jquery cookies

我只有一个带有可以隐藏的 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/

相关文章:

javascript - 如何使用 OneDrive REST API 将文件上传到 OneDrive?

reactjs - Set-Cookie 来自服务器的响应,但不存储在存储 cookie 中

Javascript:变量中的 MYSQL 查询

javascript - 在Javascript中,在本地工作时,如何从项目文件夹中读取文件并将其用作ArrayBuffer?

javascript - 我的按钮中的事件监听器无法正常工作,该功能在单击事件之外正常运行,但是当我单击按钮时它不起作用

javascript - 如何为函数设置延迟?

javascript - 如何简化具有多个 div 的切换功能

javascript - jQuery 航点错误 : The sticky method does not exist

ruby-on-rails - 设计:如何手动设置 remember_user_token cookie?

javascript - $.cookie 仅在 jquery 事件内工作,而不在 javascript 函数内工作