简体   繁体   English

会话存储购物车

[英]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 我的代码似乎无法正常工作这是git hub链接: 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: 完成此操作后,将“ display()”函数更改为如下所示:

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('');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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