我打開一個新的線程基於此how to store an array in jquery cookie?。我使用的功能從almog.ori:如何在jQuery cookie中存儲數組?
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.
$.cookie(cookieName, items);
},
"clear": function() {
//clear the cookie.
$.cookie(cookieName, null);
},
"items": function() {
//Get all the items.
return items;
}
}
}
搶指標元素上點擊事件的數組:
var list = new cookieList("test");
$(img).one('click', function(i){
while($('.selected').length < 3) {
$(this).parent()
.addClass("selected")
.append(setup.config.overlay);
//$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
var index = $(this).parent().index();
// suppose this array go into cookies.. but failed
list.add(index);
// this index goes in array
alert(list.items());
var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
if($('.total').length){
$('.total').html(count);
}
}
});
當我得到的產品清單,它返回null,但是當我在提醒onclick事件,最終將值推入該數組中。但是當我嘗試檢索返回的cookie時,它將返回null。請幫助...
另一種可能性是使用'window.JSON.stringify'(如果可用)。對更復雜的「數組/對象」可能更有意義。 – jAndy 2010-08-02 11:45:09
@jAndy - 我同意更大的情況,但在這種情況下,它是一個整數數組,因此不需要過度複雜:) – 2010-08-02 12:37:52
謝謝尼克......你是真正的救星。感謝隊友.. – fadzril 2010-08-02 13:12:18