JavaScript购物车代码运行异常求助:数量获取与商品计数逻辑故障
存在的问题与修复方案
- 价格计算逻辑错误:你创建
newItem的innerHTML时,该节点还未插入DOM,此时调用document.querySelector('.amount-items')获取到的是已存在的其他商品数量节点,或直接返回null,无法拿到当前商品的1这个初始数量,直接用单价*1即可。 - 重复商品判断逻辑错误:
- 已判断商品存在的if分支中,你依然往items数组push了当前商品,属于冗余操作,且会导致数组内重复数据越来越多
- 内部for循环重新声明了i变量,覆盖了外层监听函数的i值,导致索引完全错乱
- 数量+1的计算结果没有赋值回DOM节点,运算结果直接丢失
- 遍历items数组时,用循环的索引i去取
addToCartButtons的元素,和当前点击的商品完全不匹配
- 没有存储商品与对应DOM的映射:你只在items数组存了商品value,没有记录每个商品对应的数量、单价、DOM节点,触发更新时找不到要修改的目标元素。
修复后完整JS代码
const cartDropdown = document.querySelector('.cart-dropDown-items'); const addToCartButtons = document.querySelectorAll('.addToCart'); const foodPrices = document.querySelectorAll('.selection-row-title'); const foodNames = document.querySelectorAll('.selection-row-foodName'); const totalPriceDom = document.querySelector('.cart-dropDown-checkout2 p'); // 改用对象存储商品信息,key为商品value,value存商品的数量、单价、DOM节点 const cartItems = {}; let total = 0; for (let i = 0; i < addToCartButtons.length; i++) { const currentItemValue = addToCartButtons[i].value; const currentPrice = Number(foodPrices[i].innerHTML.substring(1)); const currentName = foodNames[i].innerHTML; addToCartButtons[i].addEventListener('click', function() { // 商品已存在的情况 if (cartItems[currentItemValue]) { // 数量+1 cartItems[currentItemValue].amount += 1; // 更新DOM数量 cartItems[currentItemValue].amountDom.textContent = cartItems[currentItemValue].amount; // 更新该商品总价 cartItems[currentItemValue].priceDom.textContent = (currentPrice * cartItems[currentItemValue].amount).toFixed(2); } // 商品不存在的情况,新增节点 else { const newItem = document.createElement('div'); newItem.className = 'dropDown-item'; const amountDom = document.createElement('p'); amountDom.className = 'amount-items'; amountDom.textContent = 1; const priceDom = document.createElement('div'); priceDom.className = 'dropDown-price dropDown-info'; priceDom.textContent = currentPrice.toFixed(2); newItem.innerHTML = `<div class='dropDown-title dropDown-info'>${currentName}</div>`; const amountWrapper = document.createElement('div'); amountWrapper.className = 'dropDown-amount dropDown-info'; amountWrapper.appendChild(amountDom); newItem.appendChild(amountWrapper); newItem.appendChild(priceDom); // 存到cartItems对象里 cartItems[currentItemValue] = { amount: 1, price: currentPrice, amountDom: amountDom, priceDom: priceDom } cartDropdown.appendChild(newItem); } // 更新购物车总价 total += currentPrice; totalPriceDom.textContent = `$${total.toFixed(2)}`; }) }
内容的提问来源于stack exchange,提问作者Ryan23442342
相关产品推荐
相关产品推荐

