简体   繁体   中英

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.

visited value does not increase and the cookie does not set a new value.

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.

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.

You don't need the else statement, try this:

$(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

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