简体   繁体   中英

pure js shopping cart

I'm trying to make a shopping cart with pure JS. I'm trying to dynamically create some divs with my products and buttons to increase/decrease/delete them, but I am stuck. Below is my function which is creating these divs:

function displayCart() {
let output = '';
for (let i in cart) {
    output += '<div class="card card-body cartc">' + '<p>' +
        '<span id="' + cart[i].name + '">' + cart[i].name + '</span>' +
        '<button class="minus">-</button>' +
        ' ' + cart[i].count + ' шт.' +
        '<button class="plus">+</button>' +
        '<button class="delete">x</button>' +
        '</p>' + '</div>';
};
document.querySelector('.cart').innerHTML = output;
document.querySelector('.total').innerHTML = totalCost();}

So the next step is to put events on buttons.

document.addEventListener("click", function (event) {
if (document.querySelector('.minus')) {
    let name = this.querySelector('.cartc span').getAttribute("id");
    removeItemFromCart(name);
    displayCart();
}});

As you can see, it finds the first .cart span id and returns it to removeItemFromCart() , but this function should work in every div that I create, not just the first one. How can it be solved?

You can take a look at the whole project at https://enoltc.github.io/hw-2/ or https://github.com/ENoLTC/hw-2/ Creating a Shopping Cart using only HTML/JavaScript The difference is that I want to write my script in pure JavaScript, without using simpleCart or jQuery.

So I did it this way

let buttons = document.getElementById("show-cart");
buttons.addEventListener("click", function (event) {
    let name = event.target.getAttribute("data-name");
    if (event.target.className === "delete") {
        removeItemFromCartAll(name);
        displayCart();
    } else if (event.target.className === "minus") {
        removeItemFromCart(name);
        displayCart();
    } else if (event.target.className === "plus") {
        addItemToCart(name, 0, 1);
        displayCart();
    }
});

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