2012-07-13 40 views
0

我的問題:下面的代碼將一個值存儲到regId中,當我再次單擊該按鈕時,此值將被覆蓋。如何在regId中存儲新值而不覆蓋regId數組中的其他值?如何將多個值添加到localstorage數組?

$('.btn-joinContest').live('click', function(e){ 
if (Modernizr.localstorage) { 
    var id = getUrlVars()["id"], 
     regId = [ ], 
     currentList = localStorage["contest"]; 

    if(currentList == null) { 
     console.log('first click add to local storage'); 
     regId.push(id); 
     localStorage['contest']=JSON.stringify(regId); 
    } 
    else if (currentList.length === 0) { 
     console.log('store contains empty value'); 
     regId.push(id); 
     localStorage['contest']=JSON.stringify(regId);  
    } else { 
     console.log('there is something in localstorage get it'); 
     regId = JSON.parse(currentList); 
    // Search for a specified value within regId array and return its index 
     // (or -1 if not found).    
     if(jQuery.inArray(id, regId) > -1){ 
      console.log('id is already in array'); 
     } else { 
      console.log('add current id to localstorage'); 
      regId.push(id); 
      localStorage['contest']=JSON.stringify(regId);     
     }    
    } 
} else { 
    console.log('this browser does not support localstorage') 
} 
}); 

回答

0
$('.btn-joinContest').live('click', function(e){ 
    id = 'Something new'; 
    currentList = localStorage["contest1"]; 
    var regId = []; 
    console.log(currentList); 
    if(currentList) 
     regId = JSON.parse(currentList); 
    regId.push(id); 
    localStorage['contest1']=JSON.stringify(regId);  
});​​ 

會是這樣的工作?

Demo: