1

我正在创建一个网页,用户可以在其中将项目添加到 Dropbox 购买单击按钮。sessionStorage 存储项目的部分和数量。下拉框将显示所选项目的详细信息(数量为 1)。如果选择了相同的项目,如何将数量更新为 2?

        $("#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++);
                }
4

1 回答 1

2

我建议您使用不同的数据结构来存储用户的购物篮。您可以使用关联数组(通过使用 JavaScript 对象)来映射partnum数量,而不是使用数组(myids) ,例如:

// 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);
}

使用地图将允许您创建辅助方法来从 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);
}

希望有帮助:)

于 2013-03-23T15:24:28.193 回答