2013-03-23 39 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); 
} 

希望帮助:)

相关问题