javascript 更新购物车页面中的产品数量

jq6vz3qz  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(141)

我在一家电子商务商店工作,我在更新购物车页面中的产品数量时遇到问题。(例如,当有人在数量标签中添加多个产品时,该数量应添加到购物车页面中,总价应根据产品的数量计算)。我已经创建了一个从右侧弹出的SideCart。欢迎任何帮助!!

const cartButton = document.getElementById('cart-button');
const cart = document.querySelector('.cart');
const cartItems = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
const addButtons = document.querySelectorAll('.add-to-cart');

let cartItemsArray = [];

function renderCartItems() {
  cartItems.innerHTML = '';
  cartItemsArray.forEach(item => {
    const li = document.createElement('li');
    li.innerHTML = `
      <img src="${item.image}" alt="${item.name}">
      <span>${item.name} x ${item.quantity}</span>
      <span>$${item.price * item.quantity}</span>
    `;
    cartItems.appendChild(li);
  });
  cartTotal.textContent = calculateCartTotal();
}

function calculateCartTotal() {
  let total = 0;
  cartItemsArray.forEach(item => {
    total += item.price * item.quantity;
  });
  return total.toFixed(2);
}

function addToCart(name, price, image) {
  const existingItem = cartItemsArray.find(item => item.name === name);
  if (existingItem) {
    existingItem.quantity++;
  } else {
    cartItemsArray.push({ name, price, image, quantity: 1 });
  }
  renderCartItems();
}

cartButton.addEventListener('click', () => {
  cart.classList.toggle('show');
});

addButtons.forEach(button => {
  const name = button.getAttribute('data-name');
  const price = button.getAttribute('data-price');
  const image = button.parentNode.querySelector('img').getAttribute('src');
  button.addEventListener('click', () => {
    addToCart(name, price, image);
  });
});
<div class="container">
        <button id="cart-button">Cart</button>
        <div class="products">
          <div class="product">
            <img src="./vision_red_front.png" alt="Product 1">
            <h3>Product 1</h3>
            <p>Price: $10</p>
            <div class="quantity">
              <span class="quantity">quantity : </span>
              <input type="number" id="num" class="quantity" oninput="calc()" min="1" max="1000" value="1" />
            </div>
    <button id="cart-button" class="add-to-cart" data-name="Product 1" data-price="10">Add to Cart</button>
          </div>

          <div class="product">
            <img src="./vision_red_front.png" alt="Product 2">
            <h3>Product 2</h3>
            <p>Price: $20</p>
            <label for="product1-quantity">Quantity:</label>
            <input type="number" id="product1-quantity" class="product-quantity" value="1">
            <button class="add-to-cart" data-name="Product 2" data-price="20">Add to Cart</button>
          </div>
</div>
        <div class="cart">
          <h3>Cart</h3>
          <ul id="cart-items"></ul>
          <p>Total: $<span id="cart-total">0</span></p>
          <a href="#"><button class="checkout" id="checkout"> Checkout</button></a>
        </div>
        
      </div>
n9vozmp4

n9vozmp41#

当按钮被按下时,需要访问inputvalue,因此当调用addToCart时,需要传递一个对button.parentNode.querySelector('input')的引用。然后可以通过JavaScript读取属性。
虽然属性是数字,但value属性是字符串,因此使用parseInt获取数字。

existingItem.quantity+=parseInt(q.value);
const cartButton = document.getElementById('cart-button');
const cart = document.querySelector('.cart');
const cartItems = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
const addButtons = document.querySelectorAll('.add-to-cart');

let cartItemsArray = [];

function renderCartItems() {
  cartItems.innerHTML = '';
  cartItemsArray.forEach(item => {
    const li = document.createElement('li');
    li.innerHTML = `
      <img src="${item.image}" alt="${item.name}">
      <span>${item.name} x ${item.quantity}</span>
      <span>$${item.price * item.quantity}</span>
    `;
    cartItems.appendChild(li);
  });
  cartTotal.textContent = calculateCartTotal();
}

function calculateCartTotal() {
  let total = 0;
  cartItemsArray.forEach(item => {
    total += item.price * item.quantity;
  });
  return total.toFixed(2);
}

function addToCart(name, price, image, q) {
  const existingItem = cartItemsArray.find(item => item.name === name);
  if (existingItem) {
    existingItem.quantity+=parseInt(q.value);
  } else {
    cartItemsArray.push({ name, price, image, quantity: 1 });
  }
  renderCartItems();
}

cartButton.addEventListener('click', () => {
  cart.classList.toggle('show');
});

addButtons.forEach(button => {
  const name = button.getAttribute('data-name');
  const price = button.getAttribute('data-price');
  const image = button.parentNode.querySelector('img').getAttribute('src');
  const quantity = button.parentNode.querySelector('input');
  button.addEventListener('click', () => 
    {addToCart(name, price, image, quantity);}
  );
});
<div class="container">
        <button id="cart-button">Cart</button>
        <div class="products">
          <div class="product">
            <img src="./vision_red_front.png" alt="Product 1">
            <h3>Product 1</h3>
            <p>Price: $10</p>
            <div class="quantity">
              <span class="quantity">quantity : </span>
              <input type="number" min=1 max=100 value=1 />
            </div>
    <button id="cart-button" class="add-to-cart" data-name="Product 1" data-price="10">Add to Cart</button>
          </div>

          <div class="product">
            <img src="./vision_red_front.png" alt="Product 2">
            <h3>Product 2</h3>
            <p>Price: $20</p>
            <label for="product1-quantity">Quantity:</label>
            <input type="number" id="product1-quantity" class="product-quantity" value="1">
            <button class="add-to-cart" data-name="Product 2" data-price="20">Add to Cart</button>
          </div>
</div>
        <div class="cart">
          <h3>Cart</h3>
          <ul id="cart-items"></ul>
          <p>Total: $<span id="cart-total">0</span></p>
          <a href="#"><button class="checkout" id="checkout"> Checkout</button></a>
        </div>
        
      </div>

相关问题