如何检查sessionstorage中是否存在某个项?

时间:2013-03-23 14:52:07

标签: javascript updates session-storage

我正在创建一个网页,用户可以将项目添加到Dropbox中,单击按钮。 sessionstorage存储项目的partnum和数量。保管箱将显示所选项目的详细信息(数量为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++);
                }

1 个答案:

答案 0 :(得分:2)

我建议您使用不同的数据结构来存储用户的购物篮。您可以使用Associative Array(通过使用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);
}

使用map可以创建帮助器方法来从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);
}

希望有所帮助:)