我使用此代码设置多个Cookie,但我只能设置两个。为什么不能设置更多的cookie?
function setCookie(c_name,value,exdays,path)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value + ("; path=/");
}
function setCookie(c_name,value,exdays,path)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value + ("; path=/");
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
var cookieToSet = "1";
for(var i=1; i<=4; i++) {
if(getCookie(i)) {
cookieToSet = i+1;
break;
}
}
setCookie(cookieToSet, 1, 365);
我想要实现的是为我的网站的回访者显示不同的消息。不仅是第一次访问,而是第四次访问。
答案 0 :(得分:0)
尝试简化代码以这种方式设置Cookie:
function setCookie(key, val){
document.cookie = key+'='+val;
}
setCookie('foo', 123);
setCookie('bar', 123);
setCookie('baz', 123);
document.body.innerHTML = document.cookie; // for demo purposes
你可以在分配之前检查cookie是否存在
function setCookie(key, val){
if (cookieExists(key)) return;
document.cookie = key+'='+val;
}
function cookieExists(key) {
return !!~document.cookie.split(';').map(function(a) {
return a.split('=')[0].trim();
}).indexOf(key);
}
function setCookies(cookies) {
var keys = Object.keys(cookies);
for (var i = 0, len = keys.length; i < len; i++){
var key = keys[i],
val = cookies[key];
if (cookieExists(key)) break;
setCookie(key, val);
}
}
var cookies = {
'foo': Date.now(),
'bar': 123,
'baz': 123
}
setCookies(cookies);
document.body.innerHTML = document.cookie;