jQuery Cookie没有节省价值

时间:2016-04-01 11:17:55

标签: jquery cookies setcookie jquery-cookie

我有jQuery Cookie插件,希望我设置一个cookie(带有expires)来在x次浏览后执行一个脚本,但是cookie不会返回浏览量的页面但返回NaN。

$(document).ready(function () {
    var visited = $.cookie('visited'); // visited = 0
    if (visited == 3) {
        execute script
    } 
    else {
        visited++;// increase counter of visits

        // set new cookie value to match visits
        var date = new Date();
        date.setTime(date.getTime() + (10 * 1000));
        $.cookie('visited', visited, {expires: date});

        return false;
    }
});

我的脚本有什么问题?

1 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function () {
var visited = 0;
if ($.cookie('visited')) {//test if cookie exist 
  visited = $.cookie('visited');
}

    if (visited == 3) {
       //
    } 
    else {
        visited++;// increase counter of visits

        // set new cookie value to match visits
        var date = new Date();
        date.setTime(date.getTime() + (10 * 1000));
        $.cookie('visited', visited, {expires: 1});

        return false;
    }
});

https://jsfiddle.net/dfL94kjh/