简体   繁体   中英

How to append a value to a cookie in javascript

It must have been 15 years since I set a cookie value with javascript ...

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?

Specify them all once eg:

var value = ['1', '2', '3', 'n'].join(',');
document.cookie = 'key=' + value;

where 'key=' + value will now be:

key=1,2,3,n

Or alternatively, read your data from cookie first and add new data:

var keycookie = // read your cookie here
keycookie += 'new stuff';
document.cookie = 'key=' + keycookie;
// 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 });
}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM