如何存储在jQuery的cookie的一个数组? [英] how to store an array in jquery cookie?

查看:89
本文介绍了如何存储在jQuery的cookie的一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储阵列在一个jQuery的cookie,任何一个可以帮助我吗?

I need to store an array in a jQuery cookie, any one help me please?

推荐答案

还没完全确定你需要什么,但我希望这会有所帮助。
这是一个示例,将允许您访问的任何页面,它只是一个样本上的项目!
它使用cookieName跨页识别它。

Still not exactly sure what you need but i hope this will help. This is a sample that will allow you to access the items on any page, its just a sample! It uses the cookieName to identify it across the pages.

//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, items.join(','));        },
    "clear": function() {
        items = null;
        //clear the cookie.
        $.cookie(cookieName, null);
    },
    "items": function() {
        //Get all the items.
        return items;
    }
  }
}  

因此​​,任何页面上,你可以得到的物品是这样的。

So on any page you can get the items like this.

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

添加项目到cookieList

Adding items to the cookieList

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

获取的所有项目作为一个数组

Getting all the items as an array

alert(list.items());

清除项目

list.clear();

您可以添加其他的东西像推很容易流行。
再次希望这有助于。

You can add additional things like push and pop quite easily. Again hope this helps.

修改
看看你是否具有IE浏览器问题的答案BRAVOS

EDIT See bravos answer if you having issues with IE

这篇关于如何存储在jQuery的cookie的一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆