如何在单击“添加到购物车”按钮时向购物车添加多个项目

4ktjp1zp  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(224)

单击“添加到购物车”按钮时,一次向购物车添加多个项目时遇到问题。我为它设置的警报显示了正确的数量,但它一次只向实际购物车添加1项。
代码如下:

const quantity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    for (let i in quantity) {
        const optionQuantity = document.createElement('option');
        optionQuantity.innerHTML = quantity[i];
        optionQuantity.setAttribute('value', quantity[i]);
        dropDownOptionsQuantity.appendChild(optionQuantity);
    }
addToCart.addEventListener('click', () => {
        let cartItems = [];
        const localStorageContent = localStorage.getItem('cart');
        if (localStorageContent === null) {
            cartItems = [];
        } else {
            cartItems = JSON.parse(localStorageContent);
        }
        let product = {
            imageUrl: response.imageUrl,
            name: response.name,
            id: response._id,
            price: response.price,
            selectColors: dropdownOptionsColors.value,
            quantity: parseInt(dropDownOptionsQuantity.value)
        };
        cartItems.push(product);
        localStorage.setItem('cart', JSON.stringify(cartItems));

        addNumCart();
    });
function addNumCart() {
    const localStorageContent = localStorage.getItem('cart');
    if (localStorageContent) {
        let cartItemsArray = JSON.parse(localStorageContent);
        let cartItemsTotal = document.querySelector('.cartItemsTotal');
        cartItemsTotal.innerHTML = cartItemsArray.length;
    }
}
addNumCart();

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题