2012-04-24 51 views
4
jQuery(document).ready(function(){ 
     if (document.cookie.indexOf('visited=true') === -1) { 
      var expires = new Date(); 
      expires.setDate(expires.getDate()+30); 
      document.cookie = "visited=true; path=/; expires="+expires.toUTCString(); 
      jQuery.colorbox({open:true,href:"<?=home_url()?>/popup/?site_type=2",iframe:true, innerWidth:"700px", innerHeight:"410px"}); 
     }     
}); 

當我關閉瀏覽器時,此cookie過期,但我希望它持續30天,直到他們再次看到彈出窗口。我的Javascript cookie在會話中過期,而不是在30天內

+0

你知道嗎,你只需要以其長格式編寫'jQuery'一次?通過將代碼封裝在'(function($){....})(jQuery);'中,無論是否使用了noConflict,都可以使用'$'。因爲你正在使用DOM就緒事件:jQuery對象也被傳遞給這個事件的函數,也就是說你可以使用'jQuery(document).ready(function($){' – ThiefMaster 2012-04-24 20:42:14

+0

http://stackoverflow.com/questions/6561687/how-can-i-set-a-cookie-to-expire-after-x-days-with-this-code-i-have – zod 2012-04-24 20:45:12

+0

也許這是你的瀏覽器cookie設置所強制的嗎?代碼似乎沒問題對我來說 – 2012-04-24 21:01:57

回答

4

而不是使用expires,請嘗試max-age(以秒爲單位)。這不涉及創建和修改Date實例。

if (document.cookie.indexOf('visited=true') === -1) { 
    document.cookie = "visited=true; path=/; max-age=2592000;"; 
+0

原來是我的瀏覽器,但這是一個很好的回答,用一個簡單的代碼,謝謝:) – 2012-04-25 02:02:36

-1

可能的選擇是使用html5 localStorage。它在IE8 +中得到了支持,並且與會話沒有任何關係,所以你不會在那裏遇到任何問題。如果你使用localStorage方法,你可能想要構建你的代碼。

var 30_DAYS = 1000 * 60 * 60 * 24 * 30; 
var msgSent = localStorage.msgSent; 
var now = new Date().getTime(); 
var diff = now - msgSent; 
if (!msgSent || msgSent > 30_DAYS) { 
    sendMsg(); 
} 

function sendMsg() { 
// do your popup thing 
localStorage.msgSent = new Date.getTime(); 
} 
+0

這並沒有回答他的問題...... – ThiefMaster 2012-04-24 20:42:36

+0

這是一個替代方案,我認爲它可以更好地服務他的目的,但是有點偏離主題也許。 – 2012-04-24 20:48:21

1

使用Cookie對象:

var CookieExpiryTime = { 
    END_OF_SESSION : 0, 
    SECOND : 1000, 
    MINUTE : 1000 * 60, 
    HOUR : 1000 * 60 * 60, 
    DAY : 1000 * 60 * 60 * 24, 
    YEAR : 1000 * 60 * 60 * 24 * 365, 
    NEVER : 1000 * 60 * 60 * 24 * 365 * 20 
} 
var Cookie = { 
    Set: function (n, v, time, path) { 
     var e = '', d; 
     if (time) { 
      d = new Date(); 
      d.setTime(d.getTime() + (time)); 
      e = "; expires=" + d.toGMTString(); 
     } 
     if (!path) path = "/"; 
     document.cookie = n + "=" + v + e + "; path="+path; 
    }, 
    Get: function (n) { 
     var match = n + "=", c = '', ca = document.cookie.split(';'), i; 
     for (i = 0; i < ca.length; i++) { 
      c=String(ca[i]).trim() 
      if (c.indexOf(match) === 0) { 
       return c.substring(match.length, c.length); 
      } 
     } 
     return null; 
    }, 
    Unset: function (n) { 
     this.Set(n, "", -1); 
    } 
}; 

只需使用下面的代碼來設置您的Cookie:

Cookie.Set("visited", "true", CookieExpiryTime.MONTH); 

就這麼簡單!

此外,30天添加到你的約會,你就必須這樣做:

expires.setDate(expires.getDate()+30*24*60*60*1000); 

由於時間以毫秒爲單位,而不是在天。

+0

通過'.setDate()'修改日期時,你處理的是日子,而不是毫秒。 – Pointy 2012-04-24 21:06:37