简体   繁体   English

jQuery cookie值不会增加

[英]jQuery cookie value doesn't increase

I want to display an alert when a visiter visits certain pages. 我想在访客访问某些页面时显示警报。

I tried this code : 我尝试了这段代码:

$(document).ready(function () {
var visited = 0;
if ($.cookie('visited')) {
visited = $.cookie('visited');
}
if (visited == 3) {
   alert('test');
} else {
    visited++;


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

    return false;
}
});

It works, but when I load my page 4 times, the value of visited stays at 3 and the alert function always display. 它可以工作,但是当我将页面加载4次时,“ visited的值保持为3,并且始终显示警报功能。

visited value does not increase and the cookie does not set a new value. visited值不会增加,并且cookie不会设置新值。

The other point is I want to set an additional parameter to my cookie: I want to display my alert function only in certain pages. 另一点是,我想为cookie设置一个附加参数:我只想在某些页面中显示警报功能。

here's how your code works. 这是您的代码的工作方式。

When visited = 0; increment visited by 1;
when visited = 1; increment visited by 1;
when visited = 2; increment visited by 1;
when visited = 3; display alert.

now your visited is always 3. Therefore, the value doesn't change. 现在您访问的总是3。因此,值不变。

You don't need the else statement, try this: 您不需要else语句,请尝试以下操作:

$(document).ready(function () {
 var visited = 0;
 if ($.cookie('visited')) {
  visited = $.cookie('visited');
 }
 if (visited == 3) {
   alert('test');
 }
 visited++;
 var date = new Date();
 date.setTime(date.getTime() + (10 * 1000));
 $.cookie('visited', visited, {expires: 1});
 return false;

});

And think to indent your code 并考虑缩进代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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