How to store array in jQuery cookie?

前端 未结 2 2074
一生所求
一生所求 2021-01-06 09:27

I\'m opening a new thread based on this how to store an array in jquery cookie?. I\'m using function from almog.ori :

var cookieList = function(cookieName) {         


        
相关标签:
2条回答
  • 2021-01-06 10:20
    var cookieList = function(cookieName) {
    
        var cookie = Cookies.get(cookieName);
        var items = cookie ? cookie.split(/,/) : new Array();
    
        return {
            "add": function(val) {
                items.push(val);
                Cookies.set(cookieName, items.join(','), {expires: new Date(2020, 0, 1)});
            },
            "remove": function(val) {
                indx = items.indexOf(val);
                if (indx != -1)
                    items.splice(indx, 1);
                Cookies.set(cookieName, items.join(','), {expires: new Date(2020, 0, 1)});
            },
            "clear": function() {
                items = null;
                Cookies.set(cookieName, null, {expires: new Date(2020, 0, 1)});
            },
            "items": function() {
                return items;
            }
        }
    };
    
    0 讨论(0)
  • 2021-01-06 10:25

    This line:

    $.cookie(cookieName, items);
    

    Should create the string from the array as well, like this:

    $.cookie(cookieName, items.join(','));
    

    This is so that when loading the array via cookie.split(/,/), it gets a string it expects (comma-delimited).

    0 讨论(0)
提交回复
热议问题