jQuery 如何在jquery cookie中存储数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1959455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to store an array in jquery cookie?
提问by mukamaivan
I need to store an array in a jQuery cookie, any one help me please?
我需要在 jQuery cookie 中存储一个数组,请有人帮我吗?
回答by almog.ori
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.
仍然不确定您需要什么,但我希望这会有所帮助。这是一个示例,可让您访问任何页面上的项目,它只是一个示例!它使用 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, 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.
Adding items to the cookieList
向 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());
Clearing the items
清除物品
list.clear();
You can add additional things like push and pop quite easily. Again hope this helps.
你可以很容易地添加额外的东西,比如 push 和 pop。再次希望这会有所帮助。
EDITSee bravos answer if you having issues with IE
编辑如果您遇到 IE 问题,请参阅 bravos 答案
回答by almog.ori
Download the jQuery cookie plugin here: http://plugins.jquery.com/project/Cookie
在此处下载 jQuery cookie 插件:http: //plugins.jquery.com/project/Cookie
Setting a cookie with jQuery is as simple as this, where we are creating a cookie called "example" with a value of ["foo1", "foo2"]
使用 jQuery 设置 cookie 就这么简单,我们创建了一个名为“example”的 cookie,其值为 ["foo1", "foo2"]
$.cookie("example", ["foo1", "foo2"]);
Getting the cookie's value is also very easy with jQuery. The following would show the value of the "example" cookie in a dialog window
使用 jQuery 获取 cookie 的值也很容易。以下将在对话窗口中显示“示例”cookie 的值
alert( $.cookie("example") );
回答by Pavel Shkleinik
Check out my implementation (as a jquery plugin):
查看我的实现(作为 jquery 插件):
(function ($) {
$.fn.extend({
cookieList: function (cookieName) {
var cookie = $.cookie(cookieName);
var items = cookie ? eval("([" + cookie + "])") : [];
return {
add: function (val) {
var index = items.indexOf(val);
// Note: Add only unique values.
if (index == -1) {
items.push(val);
$.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
}
},
remove: function (val) {
var index = items.indexOf(val);
if (index != -1) {
items.splice(index, 1);
$.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
}
},
indexOf: function (val) {
return items.indexOf(val);
},
clear: function () {
items = null;
$.cookie(cookieName, null, { expires: 365, path: '/' });
},
items: function () {
return items;
},
length: function () {
return items.length;
},
join: function (separator) {
return items.join(separator);
}
};
}
});
})(jQuery);
Usage:
用法:
var cookieList = $.fn.cookieList("cookieName");
cookieList.add(1);
cookieList.add(2);
cookieList.remove(1);
var index = cookieList.indexOf(2);
var length = cookieList.length();
回答by alhoseany
I don't know if this will help someone but I also needed the function that checks if the item already there so I do not add it again.
我不知道这是否会对某人有所帮助,但我还需要检查该项目是否已经存在的功能,因此我不会再次添加它。
I used the same remove function and alter it to be contain function:
我使用了相同的删除功能并将其更改为包含功能:
"contain": function (val) {
//Check if an item is there.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
var indx = items.indexOf(val);
if(indx>-1){
return true;
}else{
return false;
}
},
for some reason the code above does not always work. so here is the new one that works:
出于某种原因,上面的代码并不总是有效。所以这是一个有效的新方法:
"contain": function (val) {
//Check if an item is there.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
var indx = items.join(',').indexOf(val);
if(indx > -1){
return true;
}else{
return false;
}
},
回答by bravo net
I got error when I try to use almog.ori's script in IE 8
当我尝试在 IE 8 中使用 almog.ori 的脚本时出错
//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
// https://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;
}
}
}
after a few hours digging the error, i only realised that indexOf in
在挖掘错误几个小时后,我才意识到 indexOf 在
"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(',')); },
is not support in IE 8.
IE 8 不支持。
and so I add in another code base from here How to fix Array indexOf() in JavaScript for Internet Explorer browsers
所以我从这里添加了另一个代码库How to fix Array indexOf() in JavaScript for Internet Explorer browser
it works,
有用,
"remove": function (val) {
//EDIT: Thx to Assef and luke for remove.
/** indexOf not support in IE, and I add the below code **/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
var indx = items.indexOf(val);
if(indx!=-1) items.splice(indx, 1);
//if(indx!=-1) alert('lol');
$.cookie(cookieName, items.join(','));
},
just in case anyone found the script is not working in IE 8, this might help.
以防万一有人发现该脚本在 IE 8 中不起作用,这可能会有所帮助。
回答by Wessel dR
I slightly adjusted the example to use JSON encoding and secureJSON decode, making it more robust and save.
我稍微调整了示例以使用 JSON 编码和 secureJSON 解码,使其更加健壮和保存。
It depends on https://code.google.com/p/jquery-json/
这取决于https://code.google.com/p/jquery-json/
/*
* Combined with:
* http://www.terminally-incoherent.com/blog/2008/11/25/serializing-javascript-objects-into-cookies/
* With:
* https://code.google.com/p/jquery-json/
*
*/
(function ($) {
$.fn.extend({
cookieList: function (cookieName, expireTime) {
var cookie = $.cookie(cookieName);
var items = cookie ? $.secureEvalJSON(cookie) : [];
return {
add: function (val) {
var index = items.indexOf(val);
// Note: Add only unique values.
if (index == -1) {
items.push(val);
$.cookie(cookieName, $.toJSON(items), { expires: expireTime, path: '/' });
}
},
remove: function (val) {
var index = items.indexOf(val);
if (index != -1) {
items.splice(index, 1);
$.cookie(cookieName, $.toJSON(items), { expires: expireTime, path: '/' });
}
},
indexOf: function (val) {
return items.indexOf(val);
},
clear: function () {
items = null;
$.cookie(cookieName, null, { expires: expireTime, path: '/' });
},
items: function () {
return items;
},
length: function () {
return items.length;
},
join: function (separator) {
return items.join(separator);
}
};
}
});
})(jQuery);
回答by user3369864
Nice piece of code for what I am doing at the moment, but found a bug. I was saving a list of integers (IDs) to the cookie. However when the cookie is first read it typecasts to strings. I previously save (int) 1, and later when the cookie is retrieved on a page reload is designates it as "1". Thus when I try to remove (int) 1 from the list it won't index a match.
这段代码很适合我目前正在做的事情,但发现了一个错误。我正在将整数 (ID) 列表保存到 cookie。但是,当第一次读取 cookie 时,它会类型转换为字符串。我以前保存 (int) 1,后来在页面重新加载时检索 cookie 时将其指定为“1”。因此,当我尝试从列表中删除 (int) 1 时,它不会索引匹配项。
The fix I applied is to change the "val" expressions to val.toString() prior to adding or indexing the items. Thus items is an array of strings.
我应用的修复是在添加或索引项目之前将“val”表达式更改为 val.toString()。因此 items 是一个字符串数组。
"add": function(val) {
//Add to the items.
items.push(val.toString());
//Save the items to a cookie.
$.cookie(cookieName, items.join(','));
},
"remove": function (val) {
//EDIT: Thx to Assef and luke for remove.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
var indx = items.indexOf(val.toString());
if(indx!=-1) items.splice(indx, 1);
//Save the items to a cookie.
$.cookie(cookieName, items.join(','));
},
回答by Susie
This is how you store and retrieve an array in cookie using json and jquery.
这就是使用 json 和 jquery 在 cookie 中存储和检索数组的方式。
//Array
var employees = [
{"firstName" : "Matt", "lastName" : "Hendi"},
{"firstName" : "Tim", "lastName" : "Rowel"}
];
var jsonEmployees = JSON.stringify(employees);//converting array into json string
$.cookie("employees", jsonEmployees);//storing it in a cookie
var empString = $.cookie("employees");//retrieving data from cookie
var empArr = $.parseJSON(empString);//converting "empString" to an array.
回答by Pavel Shkleinik
This implementation provides independent access for multiple controls on the page:
此实现为页面上的多个控件提供独立访问:
(function ($) {
$.fn.extend({
cookieList: function (cookieName) {
return {
add: function (val) {
var items = this.items();
var index = items.indexOf(val);
// Note: Add only unique values.
if (index == -1) {
items.push(val);
$.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
}
},
remove: function (val) {
var items = this.items();
var index = items.indexOf(val);
if (index != -1) {
items.splice(index, 1);
$.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
}
},
indexOf: function (val) {
return this.items().indexOf(val);
},
clear: function () {
$.cookie(cookieName, null, { expires: 365, path: '/' });
},
items: function () {
var cookie = $.cookie(cookieName);
return cookie ? eval("([" + cookie + "])") : []; ;
},
length: function () {
return this.items().length;
},
join: function (separator) {
return this.items().join(separator);
}
};
}
});
})(jQuery);
回答by Assaf Vilmovski
I added the "remove"
action to whoever want to use it -
val
is the index at which to start changing the array:
我"remove"
向任何想要使用它的人添加了操作 -
val
是开始更改数组的索引:
"remove": function (val) {
items.splice(val, 1);
$.cookie(cookieName, items.join(','));
}