简体   繁体   中英

Session Storage Shopping Cart

I would like to add items to my shopping cart and display them in a list. My code doesn't seem to be working Here's the git hub link: GitHub

 var cart = {}; function addToCart(product){ var productName = product.getAttribute("data-name"); var price = product.getAttribute("data-price"); cart[productName] = price; alert(productName + " successfully added to cart"); console.log(cart); sessionStorage.setItem("myCart", JSON.stringify(cart)); } function getCart(){ var test = sessionStorage.getItem("myCart"); console.log(JSON.parse(test)); } function clearCart(){ sessionStorage.removeItem("myCart"); } function display(){ var cart = JSON.parse(sessionStorage.getItem("myCart")); var content=''; for (var key in cart) { var name = key; //B var price = cart[key]; //15 content += '<tr><td>'+name+'</td><td>'+price+'</td></tr>'; } document.getElementById("cartTable").innerHTML = content; } 
 <h1>My Cart</h1> <table id="cartTable"> <tr> <td>Name</td> <td>Price</td> </tr> </table> <!-- Code from index.html --> <button id="prodA" data-name="A" data-price="10" onclick="addToCart(this)">Add to cart</button> <!-- end of code --> <button id="tCart" onclick="display()">View</button> <button id="getCart" onclick="getCart()" ><a href="cart.html">View Cart</a></button> 

I suggest that you change the cart from an object to an array, and then push products directly into the cart.

Once you do this, change "display()" function to be like this:

function display() {
    var cart = JSON.parse(sessionStorage.getItem("myCart"));
    var content = document.getElementById("cartTable");

    content.innerHTML = cart.map(product => {
        return '<tr><td>' + product.name + '</td><td>' + product.price + '</td></tr>';
    }).join('');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM