2011-12-31 57 views
4

我有幾個localStorage關鍵字,例如Cart,Viewed和Trash。LocalStorage,通過匹配的ID進行循環,從DOM中刪除

的問題是雙重的:

1)如何可能我環路雖然該項目的ID中的localStorage以最高效的方式,如果一個ID已經存在,類或數據屬性添加到匹配的DOM元素。

2)從3本地存儲Keys(垃圾箱,購物車,查看)創建最後20個項目的單個列表的最佳方式是什麼?從性能角度來看,是否最好在我的問題的pt1中使用相同的循環函數來做到這一點(也就是測試一個ID是否存在並添加一個類,如果爲true)?

這是我有:

HTML

<article data-id="548" data-date="Mon Dec 19 09:12:57"> <h1><a href="#">Title</a></h1> // section // footer <a href="#" data-context="trash">trash</a> </article>

jQuery的

$tools.on("click", "a", function(e){ 
     var storeId = $(this).attr('data-context');   
     var selector = $(this).closest('article'); 
     var dataId = selector.attr('data-id'); 
     var pubDate = selector.attr('data-date'); 
     var postUrl = selector.find('a', 'h1').attr('href'); 
     var postTitle = selector.find('h1').text(); 
     var $removable = $container.find(selector); 
     setLocalStorage(storeId, dataId, postUrl, postTitle, pubDate); 
     if (storeId == "Trash") { 
        $container.isotope('remove', $removable); 
     }; 
     e.preventDefault(); 
    }); 

setter函數。

變量通過諸如data-context="Trash"(關鍵字)和data-id="001"(id)並存儲在相關密鑰中。

function setLocalStorage(itemKey, dataId, postUrl, postTitle, postPub) { 
     var ItemKey = itemKey; 
     var timeStamp = new Date(); 
     var json = JSON.parse(localStorage.getItem(ItemKey)); 
     if(json == null) 
     json = []; 
     json.push({id:dataId,title:postTitle,url:postUrl,postPub:postPub,dataTimeStamp:timeStamp}); 
     // save the result array 
     sessionStorage.setItem(ItemKey, JSON.stringify(json)) 

     // Notify user item added to Cart 
     updateNotifications(ItemKey, json); 
    } 

的localStorage的結束是這樣的:Trash [{"id":"418","title":"\n\t\t\t\t\t\t\t\t\tPost Title....//..."}]

這裏任何幫助將是非常讚賞。

新年快樂!

乾杯 本

回答

0

存放在一個關鍵的單個對象。然後在解析對象後處理它。

var mysite = $.parseJSON(localStorage['mysite']); 

您可以存儲所有國家IDS向量的陣列(例如

{ 
    cart:[idA,idB], 
    viewed:[idZ,idX], 
    trashed:[id1,id2] 
} 

然後改變狀態,無效表示狀態值的對象。林不知道你要完成的任務,但也許被視爲物品移動到低於摺疊的div,垃圾和購物車物品會自行移動到隱藏的divs,並且相應的圖標會更新爲相應的計數等。

如果這些項目已存儲在你的數據庫中,但不是生成的編輯每一頁你可以ajax請求的項目數據爲給定的ID和生成你需要他們的狀態檢索對象。

也許你想要所有這些數據存儲在本地,因爲它沒有存儲在數據庫的某個地方,更多的信息可能會有所幫助。