我想要做的事情如下(伪代码):
假设示例中的cookie名称为“visited”,且其不包含任何内容。
if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")
我怎样才能在JavaScript中实现这个?
我想要做的事情如下(伪代码):
假设示例中的cookie名称为“visited”,且其不包含任何内容。
if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")
我怎样才能在JavaScript中实现这个?
document.cookie
。if (document.cookie.indexOf("visited=") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
这是其中一种实现方式。请注意,document.cookie
是一个特殊的属性,所以您不必担心覆盖任何内容。
还有一些更方便的库来处理 cookies,如果您不需要在每个请求中将存储的信息发送到服务器,则HTML5 的 localStorage
和相关技术也非常方便和有用。
/(^|;\s?)visited=/
- Mike Causer
max-age=numseconds
来设置 cookie 在被创建后numseconds
秒后过期。请参考这里的其他答案以了解用法。 - Michael Berkowski> -1
而不是>= 0
。 - Silver Ringveeblabla_visited
。 - T.Todua