我试图找到一个干净的方式,看看我的网站的用户是否最近访问过。我需要在javascript中完成此操作(由于缓存),我已经提出了下面的代码。是否有更清洁的方法来做到这一点,即。少行代码:)
function createCookie(name,value,days) {
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = 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 c.substring(nameEQ.length,c.length);
}
return null;
}
var newuser = readCookie('newuser');
if (newuser == '1') {
[do something with x]
}
else {
createCookie('newuser','1',365);
}