这是我的脚本。
<script>
function save() {
var x=document.getElementById("user").value;
var y=document.getElementById("password").value;
document.cookie=x+" "+y;
}
function write() {
document.write(document.cookie);
}
</script>
这很好用,它会记住 var x 和 y 的值,并在调用函数 write() 时写入它们。当我关闭浏览器时,cookie 会被删除,这是应该的。但我想设置一年的到期日期;我尝试了很多方法,但我真的无法让它工作。有帮助吗?
最佳答案
添加一个最大年龄段:
;max-age=<max-age-in-seconds>
这将使您的 cookie 在一天内过期:
function save() {
var x=document.getElementById("user").value;
var y=document.getElementById("password").value;
document.cookie=x+"="+y+";max-age="+(3600*24);
}
我建议使用库来设置 cookie,因为跨浏览器设置/读取 cookie 时会遇到很多问题。 For example the js-cookie library .
注意:将纯文本密码存储在 cookie 中是不好的做法。您可能正在寻找 session cookie。
关于javascript - 如何用js设置cookies过期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422763/