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

基于数组内容更新HTML元素:JS购物车商品展示与移除功能实现问题

购物车需求实现方案

问题根因

  • 添加商品的循环逻辑反复覆盖文本内容,最终仅保留最后一次赋值的商品名
  • 移除商品逻辑只更新了购物车长度,未同步渲染商品列表
  • 未做边界校验,未添加的商品点击移除会误删其他正常商品

修复后的完整JS代码

let products = [{
    Price: 20,
    Name: "Football Helmet",
    Description: "Titans football helmet",
    Id: "Titan_a"
  },
  {
    Price: 15,
    Name: "Light Blue Shirt",
    Description: "Titans light blue shirt",
    Id: "Titan_b"
  },
  {
    Price: 15,
    Name: "White Shirt",
    Description: "Titans white shirt",
    Id: "Titan_c"
  },
  {
    Price: 15,
    Name: "Blue Shirt",
    Description: "Titans blue shirt",
    Id: "Titan_d"
  },
  {
    Price: 25,
    Name: "Hockey Stick",
    Description: "Titans hockey stick",
    Id: "Titan_e"
  }
];

let cart = [];

const addButtons = document.getElementsByClassName("add");
const removeButtons = document.getElementsByClassName("remove");
const amountLabel = document.getElementById("cartamnt");

// 抽离公共渲染函数,避免重复代码
function renderCart() {
  // 拼接所有购物车商品名称,用换行分隔
  const productNames = cart.map(item => item.Name).join('\n');
  amountLabel.innerText = `(${cart.length}) Cart: \n${productNames}`;
}

for (const addButton of addButtons) {
  addButton.addEventListener("click", () => {
    let product = products.find(p => p.Id == addButton.dataset.product);
    cart.push(product);
    // 调用渲染函数更新页面
    renderCart();
  });
}
for (const removeButton of removeButtons) {
  removeButton.addEventListener("click", () => {
    const index = cart.findIndex(p => p.Id === removeButton.dataset.product); 
    // 边界判断:只有商品存在时才执行删除
    if (index > -1) {
      cart.splice(index, 1);
    }
    // 调用渲染函数更新页面
    renderCart();
  });
}

可选CSS优化

如果要让购物车里的商品名正常换行显示,给#cartamnt添加如下属性即可:

#cartamnt {
  /* 原有属性保留,新增以下配置 */
  white-space: pre-line;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:36:03