自从我使用javascript设置Cookie值以来已经过去了15年......
document.cookie = 'key=value'; //got that ...
如何使用相同的键附加另一个值?我想创建一个值列表(页面= 1,34,48,59 ...)然后我可以读取并循环。或者有更好的方法吗?
答案 0 :(得分:4)
将它们全部指定一次,例如:
var value = ['1', '2', '3', 'n'].join(',');
document.cookie = 'key=' + value;
现在'key=' + value
将是:
key=1,2,3,n
或者,首先从cookie读取数据并添加新数据:
var keycookie = // read your cookie here
keycookie += 'new stuff';
document.cookie = 'key=' + keycookie;
答案 1 :(得分:2)
// name is cookie name
// value is cookie value
// days is life time of it
function setCookie(name,value,days) {
var date = new Date();
date.setTime(date.getTime() + ( 1000 * 60 * 60 * 24 * parseInt(days)));
parts = $.cookie(name);
if (!parts || parts == 'undefined') {
$.cookie(name, value, {path: '/', expires: date });
return;
}
parts = parts.split(",");
if (parts.length > 0) {
// search same item and delete
// if already have , delete it
for (var i=0; i<parts.length; i++) {
if (value == parts[i]) {
parts.splice(i, 1);
}
}
parts.push(value);
// if over 50, just do 50
newparts = [];
if (parts.length > 50) {
for (var i=parts.length - 50; i<parts.length; i++) {
newparts.push(parts[i]);
}
}
else {
newparts = parts;
}
$.cookie(name, newparts.join(","), {path: '/', expires: date });
}
else {
$.cookie(name, $(this).attr("id"), {path: '/', expires: date });
}};