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

如何使用jQuery实现localStorage存储购物车商品并跨页同步展示

实现localStorage购物车同步方案

核心思路

localStorage仅支持存储字符串类型数据,因此我们将购物车商品整理为JSON数组格式存储。所有购物车操作(加购、修改数量、删除、清空)都优先修改本地存储的JSON数据,再同步渲染到页面DOM,保证所有页面读取同一份存储数据实现跨页面同步。

步骤1:封装通用购物车操作函数(所有页面都需引入这段代码)

// 读取本地存储的购物车数据
function getCart() {
  return localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
}

// 将购物车数据保存到本地存储
function saveCart(cart) {
  localStorage.setItem('cart', JSON.stringify(cart));
}

// 渲染购物车数据到页面DOM
function renderCart() {
  const cart = getCart();
  const $cartList = $('#cartList');
  const $emptyCart = $('#empty-cart');
  const $badge = $('.badge');
  let totalAmount = 0;
  const shipping = 2;

  // 当前页面没有购物车容器时直接返回,避免报错
  if (!$cartList.length) return;

  // 清空现有列表避免重复渲染
  $cartList.empty();

  // 处理空购物车状态
  if (cart.length === 0) {
    $emptyCart.show();
    $badge.text(0);
    $('#total_amount_text span').text('$0');
    return;
  }
  $emptyCart.hide();

  // 遍历购物车数组生成商品DOM
  cart.forEach(item => {
    const itemPrice = item.price.replace('$', '') * 1;
    const itemTotal = itemPrice * item.quantity;
    totalAmount += itemTotal;

    const cartItem = `<li class='newItem'>
      <p class='id'>${item.id}</p>
      <div class='picture'><img src='${item.image}' ></div>
      <div class='details'>
        <p class='name'>${item.name}</p>
        <span class='weight'>${item.weight}</span><span> /</span>
        <span class='avail'>${item.availability}</span>
        <p class='price'>${item.price}</p>
        <a type='button' class='inc'>+</a>
        <input type='text' class='quantity' pattern='[0-9]+' value=${item.quantity} >
        <a type='button' class='dec'>-</a>
      </div>
      <a type='button' class='removeItem'><i class='fa fa-trash'></i></a>
    </li>`;
    $cartList.append(cartItem);
  });

  // 更新总价和购物车角标
  totalAmount += shipping;
  $('#total_amount_text span').text(`$${totalAmount.toFixed(2)}`);
  $badge.text(cart.length);
}

步骤2:替换原有加购点击逻辑

$(".addToCart").click(function(){
  const cart = getCart();
  // 获取当前点击商品的所有属性
  const newItem = {
    id: $(this).data("id"),
    price: $(this).data("price"),
    image: $(this).data('image'),
    name: $(this).data("name"),
    quantity: $(this).data("quantity"),
    availability: $(this).data("availability"),
    weight: $(this).data("weight")
  };

  // 判断商品是否已在购物车中
  const existItem = cart.find(item => item.id === newItem.id);
  if (existItem) {
    // 已存在则数量+1
    existItem.quantity += 1;
  } else {
    // 不存在则新增商品
    cart.push(newItem);
  }

  // 保存修改并刷新购物车渲染
  saveCart(cart);
  renderCart();
});

步骤3:补充其他购物车操作事件(数量修改、删除、清空)

// 商品数量增加
$(document).on('click', '.inc', function() {
  const cart = getCart();
  const id = $(this).closest('.newItem').find('.id').text() * 1;
  const targetItem = cart.find(item => item.id === id);
  targetItem.quantity += 1;
  saveCart(cart);
  renderCart();
});

// 商品数量减少
$(document).on('click', '.dec', function() {
  const cart = getCart();
  const id = $(this).closest('.newItem').find('.id').text() * 1;
  const targetItem = cart.find(item => item.id === id);
  if (targetItem.quantity > 1) {
    targetItem.quantity -= 1;
  } else {
    // 数量为1时点击减号直接删除商品
    const index = cart.findIndex(item => item.id === id);
    cart.splice(index, 1);
  }
  saveCart(cart);
  renderCart();
});

// 删除单个商品
$(document).on('click', '.removeItem', function() {
  const cart = getCart();
  const id = $(this).closest('.newItem').find('.id').text() * 1;
  const index = cart.findIndex(item => item.id === id);
  cart.splice(index, 1);
  saveCart(cart);
  renderCart();
});

// 清空整个购物车
$(document).on('click', '#clear-cart', function() {
  saveCart([]);
  renderCart();
});

步骤4:页面加载自动渲染购物车

// 页面DOM加载完成后自动渲染当前购物车数据
$(function() {
  renderCart();
});

内容的提问来源于stack exchange,提问作者Safina Siddique

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:06:00