0

是否可以在每个月的第一天删除 cookie,而不是等待 cookie 手动过期?这样我就可以每月向用户显示一次消息,无论他们查看该网站多少次。我正在使用 js-cookie。

4

1 回答 1

1

下面的代码将当前年份和月份设置为 cookie 值,例如 20173 年 2017 年 3 月。在随后的访问中,它会根据当前日期检查 cookie 值,如果当前日期更高,它会删除以前的 cookie 并创建一个新的一个与当前日期。因此,在 4 月 1 日,strDate 将是 20174,高于 20173,因此之前的 cookie 被删除并设置为新日期。

$(document).ready(function() {
     var d = new Date();
     var strYear = d.getFullYear() // cur year 
     var strMonth = d.getMonth()+1 // cur month
     var strDate = ("" + strYear + strMonth) // year + month e.g. 20173

     if (Cookies.get('cookieName') == null) { // cookie doesn't exist
        Cookies.set('cookieName', strDate, { expires: 40 }) // create cookie
        $('#modal').modal('show'); // show modal
     }
     else if (Cookies.get('cookieName') < strDate) { // cookie is older than 1 month
          Cookies.remove('cookieName'); // remove cookie to reset it
          Cookies.set('cookieName', strDate, { expires: 40 }) // create cookie
          $('#modal').modal('show'); // show modal
     }
     else {

     }
  });
于 2017-03-22T11:04:41.903 回答