2013-03-23 72 views
1

我正在創建一個網頁,用戶可以在其中添加一個項目到Dropbox購買點擊一個按鈕。 sessionstorage存儲項目的partnum和數量。 Dropbox將顯示所選項目的詳細信息(數量爲1)。如果選擇相同的項目,如何將數量更新爲2?如何檢查sessionstorage中是否存在項目?

 $("#btnBuy0").click(function() 
     { 
      $("#dropbox").append('<span><img class = "thumb" src="../images/21_metoyou.jpg" />' + teddy[0].desc + ", Price £" 
      + teddy[0].price + ", Quantity: " + quantity + "</span><br/>"); 
      if (Modernizr.sessionstorage) 
      { // check if the browser supports sessionStorage 
       myids.push(teddy[0].partnum + quantity); // add the current username to the myids array 
       sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage 
      } 
      else 
      { 
      // use cookies instead of sessionStorage 
      } 
      for (var item =0; item<sessionStroage.length; item++) 
      { 
       var key = sessionStorage.key(teddy[0].partum); 
       if (teddy[0].partnum == teddy[item].partnum) 
       { 
       var q = sesstionStorage.getItem(quantity, quantity++); 
       } 

回答

2

我建議你使用不同的數據結構來存儲用戶的購物籃。除了使用數組(myids),你可以利用的Associative Array的(通過使用JavaScript對象)映射partnum對數量,例如:

// Basket is initially empty. 
basket = {}; 

function saveOrder(teddy, quantity) { 
    var partnum = teddy[0].partnum; 

    // Create a mapping between the partnum and the quantity 
    basket[partnum] = quantity; 

    // Write the basket to sessionStorage. 
    sessionStorage.basket = JSON.stringify(basket); 
} 

使用地圖將允許你創建的helper方法讀寫從sessionStorage的,例如籃子對象:

function fetchBasketFromSession() { 
    return JSON.parse(sessionStorage.basket); 
} 

function writeBasketToSession(basket) { 
    sessionStorage.basket = JSON.stringify(basket) 
} 

function getPartNumOf(teddy) { 
    return teddy[0].partnum; 
} 

function getQuantityInSessionBasketOf(teddy) { 
    // Fetch the basket from sessionStorage 
    var sessionBasket = fetchBasketFromSession(), 
     partnum = getPartNumOf(teddy); 

    // Return the quantity mapped to the partnum in the basket, or 0 if nothing 
    // is mapped. 
    return sessionBasket[partnum] || 0; 
} 


// Combining these functions would allow you to update the users basket. 
function addToBasket(teddy, quantityToAdd) { 
    var sessionBasket = fetchBasketFromSession(), 
     currentQuantity = getQuantityInSessionBasketOf(teddy), 
     partnum = getPartNumOf(teddy); 

    // Update the quantity for this partnum and write it back out. 
    sessionBasket[partnum] = currentQuantity + quantityToAdd; 
    writeBasketToSession(sessionBasket); 
} 

希望幫助:)

相關問題