Я должен сохранить массив в cookie jQuery, кто-либо помогает мне?
До сих пор не совсем уверен, что вам нужно, но надеюсь, это поможет. Это образец, который позволит вам получить доступ к элементам на любой странице, это всего лишь образец! Он использует имя 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();
Вы можете добавлять дополнительные элементы, такие как push и pop довольно легко. Еще раз надеемся, что это поможет.
EDIT См. ответ Bravos, если у тебя проблемы с IE
.Загрузите сюда плагин jQuery для файлов cookie: http://plugins.jquery.com/project/Cookie
Установка куки с помощью jQuery так же проста, как и здесь, где мы создаем куки-файл под названием "пример" со значением ["foo1", "foo2"]
$.cookie("example", ["foo1", "foo2"]);
Получить значение куки-файла также очень просто с помощью jQuery. Далее в диалоговом окне
alert( $.cookie("example") );
Вы можете сериализовать массивы перед сохранением как cookie, а затем десериализовать при чтении. т.е. с json?