【问题标题】:jquery cookie increment each visit?jquery cookie 每次访问都会增加?
【发布时间】:2014-05-21 02:53:24
【问题描述】:

我正在使用 jquery cookies 插件,以便在每次用户访问页面时增加 cookie 的值。我这样做是为了在第一次访问时显示一些东西,然后在第二次访问时显示一些不同的东西,然后什么都没有。

所以我需要确定它是用户的第一次访问、第二次访问以及之后的所有访问。

var cookieTime = jQuery.cookie('shownDialog');
cookie_value = parseInt(cookieTime);

if (cookieTime != 'true') {         
    jQuery.cookie('shownDialog', '1', 'true', {expires: 7});
    cookie_value ++;
}

else if (cookieTime == 'true' && cookie_value > 0){
    cookie_value ++;
}

每次刷新页面时,我一直使用的这段代码都会重置。而不是将值保存在 cookie 中。我不确定保留 cookie 的值并在每次页面刷新时递增它的最佳方法?

【问题讨论】:

  • 问题是你在增加 cookie 后没有保存它。

标签: jquery jquery-cookie


【解决方案1】:

我不认为

jQuery.cookie('shownDialog', '1', 'true', {expires: 7});

是有效的形式。应该是

jQuery.cookie(cookiename, cookieval, extra);

来源:https://github.com/carhartl/jquery-cookie

如果要检查cookie是否设置,请检查它是否为null。

// Check if the cookie exists.
if (jQuery.cookie('shownDialog') == null) {
    // If the cookie doesn't exist, save the cookie with the value of 1
    jQuery.cookie('shownDialog', '1', {expires: 7});
} else {
    // If the cookie exists, take the value
    var cookie_value = jQuery.cookie('shownDialog');
    // Convert the value to an int to make sure
    cookie_value = parseInt(cookie_value);
    // Add 1 to the cookie_value
    cookie_value++;

    // Or make a pretty one liner
    // cookie_value = parseInt(jQuery.cookie('shownDialog')) + 1;

    // Save the incremented value to the cookie
    jQuery.cookie('shownDialog', cookie_value, {expires: 7});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-20
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2018-11-04
    • 2015-10-24
    相关资源
    最近更新 更多