I use the jQuery.min.js of https://github.com/carhartl/jquery-cookie and my cookie code:

$(function() {

    //hide all divs just for the purpose of this example, 
    //you should have the divs hidden with your css

    //check if the cookie is already setted
    if ($.cookie("_usci") === undefined){
            $.cookie("_usci",1);
    } else { //else..well   

            var numValue = parseInt($.cookie("_usci"));
            numValue = numValue + 1;
            else{ //no issues, assign the incremented value
                $.cookie("_usci",numValue.toString());
            }

    }


    //just to add a class number to it
    //$('.current-number').addClass($.cookie("currentDiv"));
    //to add 'n + 1/2/3/4/5/6/7/8/9/10 etc.'
    $('.current-number').addClass("n"+$.cookie("_usci"));
    $('.current-number-large').addClass("n"+$.cookie("_usci"));
});

Because of some reason when I quit my browser and open it again the cookie is not set anymore and will reset, how can I solve this?

有帮助吗?

解决方案

According to the documentation:

$.cookie('the_cookie', 'the_value', { expires: 7 });

expire define lifetime of the cookie. Value can be a Number which will be interpreted as days from time of creation or a Date object. If omitted, the cookie becomes a session cookie.

So for your case:

$.cookie('_usci', numValue.toString(), { expires: 5 * 365 });

This will make your cookie expire in five years from now.

其他提示

You must add the expire days when create the cookie:

$.cookie('the_cookie', 'the_value', { expires: 7 }); // this cookie expires in 7 days

From the documentation:

Define lifetime of the cookie. Value can be a Number which will be interpreted as days from time of creation or a Date object. If omitted, the cookie becomes a session cookie.

Being a session cookie it will be automatically deleted when the browser is closed.

In your code:

//check if the cookie is already setted
if ($.cookie("_usci") === undefined){
    $.cookie("_usci", 1, { expires: 7 });
} else {
    var numValue = parseInt($.cookie("_usci"));
    $.cookie("_usci", numValue++, { expires: 7 });
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top