当前位置:首页 > 行业动态 > 正文

html网页购物车

HTML购物车基于HTML/CSS布局,JS实现商品增删及金额计算,数据存储依赖本地或服务器

商品展示区

商品展示区用于列出可购买的商品,每个商品包含图片、名称、价格和“加入购物车”按钮,以下是一个简单的商品列表示例:

<div class="product-list">
  <div class="product">
    <img src="product1.jpg" alt="商品1">
    <h3>商品名称1</h3>
    <p>价格:¥100</p>
    <button class="add-to-cart">加入购物车</button>
  </div>
  <div class="product">
    <img src="product2.jpg" alt="商品2">
    <h3>商品名称2</h3>
    <p>价格:¥200</p>
    <button class="add-to-cart">加入购物车</button>
  </div>
</div>

购物车区域

购物车区域显示已添加的商品、数量、单价、总价,并提供修改数量和删除功能,以下是购物车的HTML结构:

<div class="cart">
  <h2>购物车</h2>
  <table>
    <thead>
      <tr>
        <th>商品名称</th>
        <th>单价</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="cart-items">
      <!-购物车商品会通过JS动态插入 -->
    </tbody>
  </table>
  <div class="cart-total">
    <span>总价:¥<span id="total-price">0</span></span>
    <button id="checkout">结算</button>
  </div>
</div>

核心功能实现

添加到购物车

通过JavaScript监听“加入购物车”按钮的点击事件,将商品信息存入localStorage或数组中。

document.querySelectorAll('.add-to-cart').forEach(button => {
  button.addEventListener('click', function() {
    const productName = this.parentElement.querySelector('h3').innerText;
    const price = parseFloat(this.parentElement.querySelector('p').innerText.replace('¥', ''));
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const existingItem = cart.find(item => item.name === productName);
    if (existingItem) {
      existingItem.quantity += 1;
    } else {
      cart.push({ name: productName, price, quantity: 1 });
    }
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCart();
  });
});

渲染购物车

localStorage读取数据并动态生成表格内容。

function updateCart() {
  const cart = JSON.parse(localStorage.getItem('cart')) || [];
  const tbody = document.getElementById('cart-items');
  tbody.innerHTML = '';
  let total = 0;
  cart.forEach((item, index) => {
    const subtotal = item.price  item.quantity;
    total += subtotal;
    const row = `<tr>
      <td>${item.name}</td>
      <td>¥${item.price}</td>
      <td>
        <button class="decrease" data-index="${index}">-</button>
        <span>${item.quantity}</span>
        <button class="increase" data-index="${index}">+</button>
      </td>
      <td>¥${subtotal}</td>
      <td><button class="remove" data-index="${index}">删除</button></td>
    </tr>`;
    tbody.insertAdjacentHTML('beforeend', row);
  });
  document.getElementById('total-price').innerText = total;
}
updateCart();

修改数量与删除商品

为“+”、“-”和“删除”按钮添加事件监听。

document.getElementById('cart-items').addEventListener('click', function(e) {
  const cart = JSON.parse(localStorage.getItem('cart')) || [];
  if (e.target.classList.contains('increase')) {
    cart[e.target.dataset.index].quantity += 1;
  } else if (e.target.classList.contains('decrease')) {
    cart[e.target.dataset.index].quantity = Math.max(1, cart[e.target.dataset.index].quantity 1);
  } else if (e.target.classList.contains('remove')) {
    cart.splice(e.target.dataset.index, 1);
  }
  localStorage.setItem('cart', JSON.stringify(cart));
  updateCart();
});

常见问题与解答

问题1:如何实现购物车的持久化存储?

解答
使用localStorage保存购物车数据,每次添加、修改或删除商品时,更新localStorage中的JSON字符串,页面加载时,从localStorage读取数据并渲染购物车。

问题2:如何优化购物车的性能?

解答

  1. 减少DOM操作:批量更新表格内容,而非频繁操作DOM。
  2. 事件委托:为购物车表格的父元素绑定事件,减少按钮的事件监听器数量。
  3. 数据缓存:将购物车数据存储在变量中,仅在必要时同步到`
0