我需要在jQuery cookie中存储一个数组,任何人都可以帮助我吗?
答案 0 :(得分:57)
仍然不确定你需要什么,但我希望这会有所帮助。 这是一个允许您访问任何页面上的项目的示例,它只是一个示例! 它使用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;
}
}
}
所以在任何页面上都可以获得这样的项目。
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();
您可以轻松添加推送和弹出等其他内容。 希望这会有所帮助。
修改强> 如果您遇到IE问题,请参阅bravos答案
答案 1 :(得分:11)
在此处下载jQuery Cookie插件:http://plugins.jquery.com/project/Cookie
使用jQuery设置cookie就像这样简单,我们创建一个名为“example”的cookie,其值为[“foo1”,“foo2”]
$.cookie("example", ["foo1", "foo2"]);
使用jQuery获取cookie的值也很容易。以下将在对话框窗口中显示“example”cookie的值
alert( $.cookie("example") );
答案 2 :(得分:3)
查看我的实现(作为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);
用法:
var cookieList = $.fn.cookieList("cookieName");
cookieList.add(1);
cookieList.add(2);
cookieList.remove(1);
var index = cookieList.indexOf(2);
var length = cookieList.length();
答案 3 :(得分:3)
当我尝试在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;
}
}
}
在挖掘错误几个小时之后,我才意识到
中的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(',')); },
不支持IE 8。
所以我从这里添加另一个代码库How to fix Array indexOf() in JavaScript for Internet Explorer browsers
它有效,
"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(','));
},
如果有人发现脚本在IE 8中不起作用,这可能会有所帮助。
答案 4 :(得分:3)
我不知道这是否会对某人有所帮助,但我还需要检查项目是否已存在的功能,所以我不再添加它。
我使用了相同的删除功能并将其改为包含函数:
"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;
}
},
由于某种原因,上面的代码并不总是有效。所以这是新的工作:
"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;
}
},
答案 5 :(得分:2)
此实现为页面上的多个控件提供独立访问权限:
(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);
答案 6 :(得分:2)
我稍微调整了示例以使用JSON编码和secureJSON解码,使其更加健壮并节省。
取决于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);
答案 7 :(得分:2)
目前正在做的很好的代码,但发现了一个错误。我正在将一个整数列表(ID)保存到cookie中。但是,当首次读取cookie时,它会转换为字符串。我以前保存(int)1,稍后当在页面上检索cookie时,重新加载将其指定为“1”。因此,当我尝试从列表中删除(int)1时,它不会索引匹配。
我应用的修复是在添加或索引项目之前将“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(','));
},
答案 8 :(得分:2)
这是使用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.
答案 9 :(得分:1)
我向想要使用它的人添加了"remove"
动作 -
val
是开始更改数组的索引:
"remove": function (val) {
items.splice(val, 1);
$.cookie(cookieName, items.join(','));
}
答案 10 :(得分:1)
只是"remove"
函数的一个小替代品:
"removeItem": function (val) {
indx = items.indexOf(val);
if(indx!=-1) items.splice(indx, 1);
$.cookie(cookieName, items.join(','));
}
其中val
是数组中项目的值,例如:
>>> list.add("foo1");
>>> list.add("foo2");
>>> list.add("foo3");
>>> list.items();
["foo1", "foo2", "foo3"];
>>> list.removeItem("foo2");
>>> list.items();
["foo1", "foo3"];
答案 11 :(得分:0)
您可以在存储为cookie之前序列化数组,然后在读取时反序列化。即与json?
答案 12 :(得分:0)
以下是使用Cookie的 JSON 实现,更好的方式来存储数组。从我的结局测试。
$.fn.extend({
cookieList: function (cookieName) {
var cookie = $.cookie(cookieName);
var storedAry = ( cookie == null ) ? [] : jQuery.parseJSON( cookie );
return {
add: function (val) {
var is_Arr = $.isArray( storedAry );
//console.log(storedAry);
if( $.inArray(val, storedAry) === -1 ){
storedAry.push(val);
//console.log('inside');
}
$.cookie( cookieName, JSON.stringify(storedAry), { expires : 1 , path : '/'});
/*var index = storedAry.indexOf(val);
if (index == -1) {
storedAry.push(val);
$.cookie(cookieName, storedAry.join(','), { expires: 1, path: '/' });
}*/
},
remove: function (val) {
storedAry = $.grep(storedAry, function(value) {
return value != val;
});
//console.log('Removed '+storedAry);
$.cookie( cookieName, JSON.stringify(storedAry), { expires : 1 , path : '/'});
/*var index = storedAry.indexOf(val);
if ( index != -1 ){
storedAry.splice( index, 1 );
$.cookie(cookieName, storedAry.join(','), { expires: 1, path: '/' });
}*/
}
clear: function () {
storedAry = null;
$.cookie(cookieName, null, { expires: 1, path: '/' });
}
};
}
});