2016-08-18 98 views
0

我正在設置一個cookie來啓動頁面加載模式。 目前,模態只發生一次。設置Cookie到期時間

我需要它重置每個月,以便它不斷彈出每個訪問者每月一次。

是否有可能修改我的代碼,使之發生或我需要以另一種方式做到這一點?任何幫助讚賞。

$(document).ready(function() { 
//if cookie hasn't been set... 
if (document.cookie.indexOf("ModalShown=true")<0) { 
    $("#newsletterModal").modal("show"); 
    //Modal has been shown, now set a cookie so it never comes back 
    $("#newsletterModalClose").click(function() { 
     $("#newsletterModal").modal("hide"); 
    }); 
    document.cookie = "ModalShown=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/"; 
} 

});

回答

2

只要不設置您的Cookie的靜態到期日期,而是一個動態之一:

var now = new Date(); //get the current date 
now.setMonth(now.getMonth() + 1); //add one month to it 
document.cookie = "ModalShown=true; expires=" + now.toUTCString() + "; path=/"; 
1

嘿,我要給簡單的代碼來設置刪除和添加的cookie,可能會幫助你

function setCookie(name, value, expire) { 
    document.cookie = name + "=" + escape(value) + ((expire === null) ? "" : ("; expires=" + expire.toGMTString())); 
} 

function checkCookie(name) { 
    if (document.cookie !== "") { 
     var toCookie = document.cookie.split("; "); 
     for (var i = 0; i < toCookie.length; i++) { 
      var CookieName = toCookie[i].split("=")[0]; 
      var CookieValue = toCookie[i].split("=")[1]; 
      if (CookieName === name) return unescape(CookieValue); 
     } 

    } 
} 

function removeCookie() { 
    var CookieAlert; 
    CookieAlert = document.getElementById('cookie'); 
    var expire = new Date(); 
    expire.setMonth(expire.getMonth() + 1); 
    setCookie('agreeCookies', 'yes', expire); 
} 

window.onload = (function() { 
    //IF cookie exists do something 
    if (checkCookie('agreeCookies') !== 'yes') { 
     //Do something in your case dont start modal 
    } else { 
     //START MODAL 
    } 
}); 

所以在HTML中可以使用的onclick =「removeCookie()」在你的模態關閉按鈕,基本上你展示模式和關閉模式設置cookie,那麼一個月後,當Cookie過期您再次顯示它

+1

請小心使用['toGMTString()'](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString)此功能已棄用:'棄用 This功能已從Web標準中刪除。儘管一些瀏覽器可能仍然支持它,但它正在被丟棄。不要在舊項目或新項目中使用它。使用它的頁面或Web應用程序可能會隨時中斷。# – empiric

+0

哦,很高興知道謝謝@empiric :) –

0

您只需將有效期限更新爲現在+ 1個月,而不是'週五,9999年12月31日23:59:59 GMT',但是請在Cookie檢查之外進行,以確保現有用戶舊的失效日期得到一個更新的cookie。