如何实现各商品的添加/移除计数独立存储与展示?
问题描述
点击添加/移除按钮时,对应商品的计数会被所有商品共享。如何实现每个商品拥有独立的计数,添加/移除时仅操作该商品的计数,且各商品计数互不干扰?
现有代码
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="header margin-bottom"> <ul> <li><a href="index.html">Home</a></li> <li><a href="#">Full Web Projects</a></li> <li class="dropdown"> <a href="javascript:void(0)" class="dropbtn">Small Projects</a> <div class="dropdown-content"> <a href="cart.html">cart</a> <a href="counter.html">Counter</a> <a href="products.html">Products</a> <a href="#">Link 3</a> </div> </li> </ul> </div> <div class="page"> <h2>Product Page</h2> <p id="message"></p> <div class="products container"> <div class="product"> <figure id="caption"> <img src="images/flower.png" alt="Flowers" /> <figcaption id="flower-caption">Beautiful Flower</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/parrot.png" alt="Flowers" /> <figcaption id="parrot-caption">Parrot</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/penguin.png" alt="penguin" /> <figcaption id="penguin-caption">Penguin</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/be-nice.png" alt="be-nice" /> <figcaption id="be-nice-caption">Be Nice</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/painting-1.png" alt="Painting-1" /> <figcaption id="painting-1-caption">Painting-1</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/painting-2.png" alt="Painting-2" /> <figcaption id="painting-2-caption">Painting-2</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/painting-3.png" alt="Painting-3" /> <figcaption id="painting-3-caption">Painting-3</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> <div class="product"> <figure id="caption"> <img src="images/painting-4.png" alt="Painting-4" /> <figcaption id="painting-4-caption">Painting-4</figcaption> </figure> <div class="productButtons"> <button type="button" class="addProduct">Add To Cart</button> <button type="button" class="removeProduct"> Remove From Cart </button> </div> </div> </div> </div> <script src="product.js"></script> </body> </html>
JavaScript代码
let count = 0; document.querySelectorAll(".addProduct").forEach((btn) => { btn.addEventListener("click", () => { const productElement = btn.closest(".product"); const proName = productElement.querySelector("figcaption").textContent; count++; if (count <= 10) { document.getElementById( "message" ).textContent = ` ${count} ${proName} Added.`; } else { count = 10; document.getElementById("message").textContent = ` Maximum limit reached`; } }); }); document.querySelectorAll(".removeProduct").forEach((btn) => { btn.addEventListener("click", () => { const productElement = btn.closest(".product"); const proName = productElement.querySelector("figcaption").textContent; count--; if (count >= 0) { document.getElementById( "message" ).textContent = ` ${count} ${proName} Remaining.`; } else { count = 0; document.getElementById("message").textContent = ` Minimum limit reached`; } }); });
尝试方案
之前用全局count变量存储计数,导致所有商品共用同一个数值,无法实现独立计数。
解决方案
问题核心在于全局变量被所有商品共享,我们需要给每个商品单独存储计数。可以用一个对象来记录每个商品的当前数量,键用商品名称(确保唯一),值为对应计数。
修改后的JavaScript代码如下:
// 用对象存储每个商品的计数,初始为空,默认计数为0 const cartCounts = {}; const MAX_LIMIT = 10; document.querySelectorAll(".addProduct").forEach((btn) => { btn.addEventListener("click", () => { const productElement = btn.closest(".product"); const proName = productElement.querySelector("figcaption").textContent; // 如果该商品还没记录,初始化为0 if (!cartCounts[proName]) { cartCounts[proName] = 0; } // 增加计数,不超过上限 if (cartCounts[proName] < MAX_LIMIT) { cartCounts[proName]++; document.getElementById("message").textContent = `${cartCounts[proName]} ${proName} Added.`; } else { document.getElementById("message").textContent = `${proName} 已达最大购买上限(${MAX_LIMIT})`; } }); }); document.querySelectorAll(".removeProduct").forEach((btn) => { btn.addEventListener("click", () => { const productElement = btn.closest(".product"); const proName = productElement.querySelector("figcaption").textContent; // 确保商品有记录且计数大于0时才减少 if (cartCounts[proName] && cartCounts[proName] > 0) { cartCounts[proName]--; document.getElementById("message").textContent = `${cartCounts[proName]} ${proName} Remaining.`; } else { // 没有商品时重置计数为0 cartCounts[proName] = 0; document.getElementById("message").textContent = `${proName} 已达最小数量(0)`; } }); });
改动说明
- 移除全局
count变量,改用cartCounts对象存储每个商品的独立计数,商品名称作为唯一标识。 - 设置
MAX_LIMIT常量统一管理最大购买数量,方便后续修改。 - 添加商品时,先检查该商品是否已有计数,没有则初始化为0,再执行递增操作,同时判断是否超过上限。
- 移除商品时,检查计数是否大于0,避免出现负数,计数为0时提示最小数量。
这样每个商品的计数就完全独立,操作某个商品时只会修改它自己的计数,不会影响其他商品。
内容的提问来源于stack exchange,提问作者Baljinder
相关产品推荐
相关产品推荐

