简体   繁体   中英

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:

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

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

Your problem is that you are writing a boolean to your cookie, which is translated to a string on write to the cookie. Reading back from the cookie does not translate in reverse. So no matter whether you put true or false in the cookie, your check for

if ( valeur_id == true)

always evaluates to boolean true. This is because "true" and "false" are both strings which evaluate to "truthy" in such a check.

If you want to stick with that library, you should write strings to the cookie and expect strings on read.

$.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. Your first block of code overwrites whatever was set by clicks on previous page loads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM