我有下一个代码:
检查我的 cookie 是否存在,如果不存在,则创建名为 value 的 cookie 在其他内部,我再次读取cookie并检查值是否为1,这里我想设置一个新值,但不更改此cookie的过期日期和时间,仅更新值
if( readCookie("value")==null)
{
createCookie("value",1,1);
}
else
{
if(readCookie("value")==1)
{
/*here I would like to set to cookie called value the new value to 2 */
}
else
{
alert("no es uno");
}
}
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
最佳答案
虽然您无法直接检查到期日期,但在设置 cookie 时,您可以将到期日期存储为 cookie 的一部分。然后,每当您想检查到期日期时,您都可以查看 cookie 的该部分。要更改 cookie 而不影响到期日期,只需重新创建 cookie,替换到期日期即可。
document.cookie="username=John Doe Thu, 18 Dec 2013 12:00:00 UTC; expires=Thu, 18 Dec 2013 12:00:00 UTC";
您始终可以在创建 Cookie 时更改 Cookie 的到期日期。
关于javascript - 如何更新 cookie 值(而不更改过期日期)? javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35900269/