Javascript 如何在javascript中将值附加到cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9075131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append a value to a cookie in javascript
提问by uwe
It must have been 15 years since I set a cookie value with javascript ...
自从我用 javascript 设置 cookie 值肯定有 15 年了......
document.cookie = 'key=value'; //got that ...
How do I append another value with the same key? I want to create a list of values (page=1,34,48,59...) that I can then read and loop over. Or is there a better way?
如何使用相同的键附加另一个值?我想创建一个值列表 (page=1,34,48,59...),然后我可以读取和循环。或者,还有更好的方法?
回答by Sarfraz
Specify them all once eg:
一次指定它们,例如:
var value = ['1', '2', '3', 'n'].join(',');
document.cookie = 'key=' + value;
where 'key=' + value
will now be:
'key=' + value
现在在哪里:
key=1,2,3,n
Or alternatively, read your data from cookie first and add new data:
或者,首先从 cookie 读取数据并添加新数据:
var keycookie = // read your cookie here
keycookie += 'new stuff';
document.cookie = 'key=' + keycookie;
回答by Cataclysm
// 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 });
}};