You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery实现购物车数量增减及商品添加功能(PHP后端)

问题诊断与修复步骤

1. 核心事件绑定不匹配问题

  • 加入购物车按钮:原JS绑定.add-to-cart类,但HTML中仅<i>标签有add-to-cart-btn,需给按钮本身添加add-to-cart类。
  • 数量输入框:原JS查找.quantity-input,但HTML输入框无此类名,需补充该类。
  • 加减按钮:原JS依赖data-action属性判断增减,需给btn-minus加data-action="decrease",btn-plus加data-action="increase"。

2. 硬编码数据问题

原JS中商品名称、价格为硬编码,需改为读取HTML的data-*属性,保证数据一致性。

3. 语法错误

原JS末尾多了一个冗余的});,需删除避免报错。

4. 购物车联动逻辑缺失

原代码仅修改详情页数量输入框,未关联已加入购物车的商品数量,需补充联动逻辑。


修复后的完整代码

HTML部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Shop Detail Start -->
<div class="container-fluid py-5">
  <div class="row px-xl-5">
    <div class="col-lg-5 pb-5">
      <div id="product-carousel" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner border">
          <div class="carousel-item active">
            <img class="w-100 h-100" src="img/product-1.jpg" alt="Image">
          </div>
          <div class="carousel-item">
            <img class="w-100 h-100" src="img/product-2.jpg" alt="Image">
          </div>
          <div class="carousel-item">
            <img class="w-100 h-100" src="img/product-3.jpg" alt="Image">
          </div>
          <div class="carousel-item">
            <img class="w-100 h-100" src="img/product-4.jpg" alt="Image">
          </div>
        </div>
        <a class="carousel-control-prev" href="#product-carousel" data-slide="prev">
          <i class="fa fa-2x fa-angle-left text-dark"></i>
        </a>
        <a class="carousel-control-next" href="#product-carousel" data-slide="next">
          <i class="fa fa-2x fa-angle-right text-dark"></i>
        </a>
      </div>
    </div>

    <div class="col-lg-7 pb-5">
      <h3 class="font-weight-semi-bold">Colorful Stylish Shirt</h3>
      <div class="d-flex mb-3">
        <div class="text-primary mr-2">
          <small class="fas fa-star"></small>
          <small class="fas fa-star"></small>
          <small class="fas fa-star"></small>
          <small class="fas fa-star-half-alt"></small>
          <small class="far fa-star"></small>
        </div>
        <small class="pt-1">(50 Reviews)</small>
      </div>
      <h3 class="font-weight-semi-bold mb-4 product-price">R150.00</h3>

      <div class="d-flex align-items-center mb-4 pt-2">
        <div class="input-group quantity mr-3" style="width: 130px;">
          <div class="input-group-btn">
            <button class="btn btn-primary btn-minus" data-action="decrease">
              <i class="fa fa-minus"></i>
            </button>
          </div>
          <input type="text" class="form-control bg-secondary text-center quantity-input" value="1">
          <div class="input-group-btn">
            <button class="btn btn-primary btn-plus" data-action="increase">
              <i class="fa fa-plus"></i>
            </button>
          </div>
        </div>
        <button class="btn btn-primary px-3 add-to-cart" 
                data-id="1"
                data-product-name="Colorful Stylish Shirt"
                data-product-price="150.00">
          <i class="fa fa-shopping-cart mr-1"></i> Add To Cart
        </button>
      </div>
    </div>
  </div>
</div>
<!-- 购物车展示区域 -->
<div class="cart-container">
  <span class="cart-badge">0</span>
  <ul id="cart-items"></ul>
  <div id="cart-total">R0.00</div>
</div>

JavaScript部分

$(document).ready(function() {
  var cart = [];
  var cartBadge = $(".cart-badge");
  var cartTotal = $("#cart-total");
  var cartItems = $("#cart-items");

  // 更新购物车展示
  function updateCartDisplay() {
    let total = 0;
    cartItems.empty();

    cart.forEach(item => {
      const itemTotal = item.price * item.quantity;
      total += itemTotal;
      // 给购物车项添加加减按钮
      cartItems.append(`
        <li>
          ${item.name} 
          <button class="cart-btn-minus" data-name="${item.name}">-</button>
          <span>数量: ${item.quantity}</span>
          <button class="cart-btn-plus" data-name="${item.name}">+</button>
          - 小计: R${itemTotal.toFixed(2)}
        </li>
      `);
    });

    cartBadge.text(cart.length);
    cartTotal.text(`R${total.toFixed(2)}`);
    updateServerCart();
  }

  // 加入购物车事件
  $(".add-to-cart").on("click", function(e) {
    e.preventDefault();
    const productName = $(this).data("product-name");
    const productPrice = parseFloat($(this).data("product-price"));
    const productQuantity = parseInt($(this).siblings(".quantity").find(".quantity-input").val());

    const existingItemIndex = cart.findIndex(item => item.name === productName);
    if (existingItemIndex !== -1) {
      cart[existingItemIndex].quantity += productQuantity;
    } else {
      cart.push({
        name: productName,
        price: productPrice,
        quantity: productQuantity
      });
    }

    updateCartDisplay();
  });

  // 详情页数量调整事件
  $(".btn-minus, .btn-plus").on("click", function() {
    const action = $(this).data("action");
    const inputField = $(this).siblings(".quantity-input");
    let currentQuantity = parseInt(inputField.val());

    if (action === "increase") {
      currentQuantity += 1;
    } else if (action === "decrease" && currentQuantity > 1) {
      currentQuantity -= 1;
    }
    inputField.val(currentQuantity);

    // 同步已加入购物车的商品数量
    const productName = $(this).closest(".col-lg-7").find(".add-to-cart").data("product-name");
    const existingItemIndex = cart.findIndex(item => item.name === productName);
    if (existingItemIndex !== -1) {
      cart[existingItemIndex].quantity = currentQuantity;
      updateCartDisplay();
    }
  });

  // 购物车内数量调整事件(事件委托处理动态元素)
  $(document).on("click", ".cart-btn-minus, .cart-btn-plus", function() {
    const isPlus = $(this).hasClass("cart-btn-plus");
    const productName = $(this).data("name");
    const existingItemIndex = cart.findIndex(item => item.name === productName);

    if (existingItemIndex !== -1) {
      if (isPlus) {
        cart[existingItemIndex].quantity += 1;
      } else if (cart[existingItemIndex].quantity > 1) {
        cart[existingItemIndex].quantity -= 1;
      }
      updateCartDisplay();
    }
  });

  // 更新后端购物车
  function updateServerCart() {
    $.ajax({
      type: "POST",
      url: "makeup-cart.php",
      data: {
        action: 'updateCart',
        cart: JSON.stringify(cart)
      },
      success: function() {
        console.log("后端购物车更新成功");
      }
    });
  }

  // 从后端获取购物车
  function getServerCart() {
    $.ajax({
      type: "POST",
      url: "makeup-cart.php",
      data: {
        action: 'getCart'
      },
      success: function(data) {
        cart = JSON.parse(data) || [];
        updateCartDisplay();
      }
    });
  }

  // 初始化购物车
  getServerCart();
});

关键修复说明

  1. 事件匹配:统一了按钮类名和属性,确保事件正确触发。
  2. 动态数据:从data-*属性读取商品信息,避免硬编码。
  3. 购物车内调整:给购物车项添加加减按钮,通过事件委托处理动态生成元素。
  4. 联动逻辑:修改详情页数量时,自动同步已加入购物车的商品数量。
  5. 后端同步:每次更新购物车后自动同步后端数据。

内容的提问来源于stack exchange,提问作者MyLegend2020 Wilson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:35:55