如何在jquery cookie中存储数组?

前端之家收集整理的这篇文章主要介绍了如何在jquery cookie中存储数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在jQuery cookie中存储数组,任何一个可以帮我吗?

解决方法

仍然不能确定你需要什么,但我希望这将有所帮助。
这是一个示例,可以让您访问任何页面上的项目,它只是一个示例!
它使用cookieName来标识页面
//This is not production quality,its just demo code.
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.
        //EDIT: Modified from linked answer by Nick see 
        //      http://stackoverflow.com/questions/3387251/how-to-store-array-in-jquery-cookie
        $.cookie(cookieName,items.join(','));
    },"remove": function (val) { 
        //EDIT: Thx to Assef and luke for remove.
        indx = items.indexOf(val); 
        if(indx!=-1) items.splice(indx,1); 
        $.cookie(cookieName,'));        },"clear": function() {
        items = null;
        //clear the cookie.
        $.cookie(cookieName,null);
    },"items": function() {
        //Get all the items.
        return items;
    }
  }
}

所以在任何页面上,你可以得到这样的项目。

var list = new cookieList("MyItems"); // all items in the array.

将项目添加到cookieList

list.add("foo"); 
//Note this value cannot have a comma "," as this will spilt into
//two seperate values when you declare the cookieList.

将所有项目作为数组

alert(list.items());

清理物品

list.clear();

你可以很容易地添加其他的东西,如push和pop。
再次希望这有帮助。

编辑如果您有IE的问题,请参阅bravos答案

猜你在找的jQuery相关文章