如何在jQuery cookie中存储数组?

时间:2010-08-02 11:26:46

标签: jquery

我正在根据此how to store an array in jquery cookie?打开一个新主题。我正在使用almog.ori的函数:

var cookieList = function(cookieName) {
//When the cookie is saved the items will be a comma seperated string
//So we will split the cookie by comma to get the original array
var cookie = $.cookie(cookieName);
//Load the items or a new array if null.
var items = cookie ? cookie.split(/,/) : new Array();

//Return a object that we can use to access the array.
//while hiding direct access to the declared items array
//this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html
return {
    "add": function(val) {
        //Add to the items.
        items.push(val);
        //Save the items to a cookie.
        $.cookie(cookieName, items);
    },
    "clear": function() {
        //clear the cookie.
        $.cookie(cookieName, null);
    },
    "items": function() {
        //Get all the items.
        return items;
    }
  }
}

在点击事件中获取索引元素数组:

var list = new cookieList("test");
$(img).one('click', function(i){
while($('.selected').length < 3) {
    $(this).parent()
        .addClass("selected")
        .append(setup.config.overlay);

    //$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
    var index = $(this).parent().index();

    // suppose this array go into cookies.. but failed
    list.add( index );
    // this index goes in array
    alert(list.items());

    var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
    if( $('.total').length ){
        $('.total').html(count);
    }

} 
});

当我获取项目列表时,它返回null但是当我在onclick事件中发出警报时,最终它会将值推送到该数组中。但是当我试图检索回cookie时,它返回null。请帮忙......

2 个答案:

答案 0 :(得分:10)

这一行:

$.cookie(cookieName, items);

也应该从数组中创建字符串,如下所示:

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

这样,当通过cookie.split(/,/)加载数组时,它会获得一个预期的字符串(以逗号分隔)。

答案 1 :(得分:0)

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;
        }
    }
};