2010-08-02 132 views
4

我打開一個新的線程基於此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。請幫助...

回答

10

這條線:

$.cookie(cookieName, items); 

應該建立該數組中的字符串,以及像這樣:

$.cookie(cookieName, items.join(',')); 

這是這樣,通過cookie.split(/,/)裝載數組時,它會得到一個字符串(逗號分隔)。

+1

另一種可能性是使用'window.JSON.stringify'(如果可用)。對更復雜的「數組/對象」可能更有意義。 – jAndy 2010-08-02 11:45:09

+0

@jAndy - 我同意更大的情況,但在這種情況下,它是一個整數數組,因此不需要過度複雜:) – 2010-08-02 12:37:52

+0

謝謝尼克......你是真正的救星。感謝隊友.. – fadzril 2010-08-02 13:12:18

0
var cookieList = function(cookieName) { 

    var cookie = Cookies.get(cookieName); 
    var items = cookie ? cookie.split(/,/) : new Array(); 

    return { 
     "add": function(val) { 
      items.push(val); 
      Cookies.set(cookieName, items.join(','), {expires: new Date(2020, 0, 1)}); 
     }, 
     "remove": function(val) { 
      indx = items.indexOf(val); 
      if (indx != -1) 
       items.splice(indx, 1); 
      Cookies.set(cookieName, items.join(','), {expires: new Date(2020, 0, 1)}); 
     }, 
     "clear": function() { 
      items = null; 
      Cookies.set(cookieName, null, {expires: new Date(2020, 0, 1)}); 
     }, 
     "items": function() { 
      return items; 
     } 
    } 
};