2015-12-15 29 views
0

發現使用sessionStorage顯示最近查看的產品的腳本非常好。只有一個問題:每個產品都可以存儲並顯示多次。sessionStorage如果值已存在

這裏的jsfiddle http://jsfiddle.net/r77oozh8/

應該有一個更IF檢查,如果目前的產品已經在存儲,這樣的事情:

// check if product already in storage 
if(!productExistsInStorage()) { 

    var currentCount = parseInt(sessionStorage.getItem("storedCount")); 

    // add to storage 
    sessionStorage.setItem(currentCount.toString(), JSON.stringify(productInfo())); 

    // update storedCount var by one 
    sessionStorage.setItem("storedCount", (currentCount + 1).toString()); 

} 

我試圖使它,但沒有成功。

任何提示如何不保存產品數據,如果它已經在sessionStorage中設置?

回答

-1

爲什麼不檢查該項目的會話存儲是否爲空?

if(sessionStorage.getItem("storedCount") === null) 
{ 
//do something 
} 

更好的做一個函數,你可以傳遞一個項目的名字來檢查它。

function doesStorageExist(item) 
{ 

if(sessionStorage.getItem(""+item) === null) 
{ 
//do something 
} 

} 
+0

因爲OP關心物品的內容。 ID不斷遞增。 – Scimonster

+0

這個問題沒有意義。你是否試圖在會話存儲中增加一個計數變量?! –

+0

我瞭解問題的方式,用戶可以將項目添加到他們的存儲。每次,它都會被賦予一個新的ID,即使實際的物品已經存在。因此,內容需要檢查,而不僅僅是數字。 – Scimonster

0

代替在sessionStorage爲每個產品設置單獨項目的,我會設置它們全部在一個陣列。這將更容易檢查它是否已經存在:

var currentItems = JSON.parse(sessionStorage.getItem('products')); 
var currentProduct = productInfo(); 
if (currentItems.filter(function(p){return p.productURL == currentProduct.productURL}).length == 0) { 
// add 
} 
+0

錯誤日誌「sessionStorage.get不是函數」 – Toon

+0

Typo。應該是'getItem' – Scimonster

+0

嗯,謝謝,但我不能按照你的建議重寫代碼(將產品數據保存到數組中)。我太喜歡這個了:/ – Toon