如何解决购物车结算页仅显示最后添加商品的问题?
问题:结算页仅显示购物车中最后添加的商品
测试步骤:
- 添加带有MP3许可证、价格20美元的商品;
- 添加带有Un-Tagged Wav许可证、价格30美元的商品;
- 点击“Continue to purchase”按钮;
- 正常跳转至checkout.html页面;
- 页面指定div仅显示最后添加的商品,而非全部已添加商品。
商品页添加购物车功能代码
<header> <!--Nav--> <div class="nav container"> <a href="">Deni Beatz</a> <!--Cart Icon--> <i class="bx bx-shopping-bag" id="cart-icon"></i> <div class="notification" id="cart-notification">0</div> <!--Cart--> <div class="cart"> <h2 class="cart-title">Your Cart</h2> <!--Content--> <div class="cart-content"> <div class="cart-content"> </div> </div> <!--Total--> <div class="total"> <div class="total-title">Total</div> <div class="total-price" id="total-price total">$0</div> </div> <!--Buy Button--> <form action="checkout.html"> <button type="button" class="btn-buy" onclick="window.location.href = 'checkout.html';">Continue to purchase</button> </form> <!--Cart Close--> <i class="bx bx-x" id="close-cart"></i> <!-- Continue to purchase button moved here --> </div> </div> </header> <section id="prodetails" class="section-p1"> <div class="productcontainer" id="enjoy"> <div class="single-pro-image"> <img src="../data/high.png" width="100%" id="product-image" class="product-img"> </div> <div class="single-pro-details" action="C:\s\starter-ruby\client\checkout.html"> <h4 class="product-title" id="title">Enjoy</h4> <h2 id="price" class="price">$20</h2> <select id="select" class="licence"> <option>Select Licence</option> <option>MP3</option> <option>Tagged Wav</option> <option>Un-Tagged Wav</option> <option>Stems</option> <option>Exlusive</option> </select> <script> let select = document.getElementById('select'); let price = document.getElementById('price'); // Prices let prices = { "Select Licence": '$20', "MP3": '$20', "Tagged Wav": '$27', "Un-Tagged Wav": '$30', "Stems": '$120', "Exlusive": '$300' } // When the value of select changes, this event listener fires and changes the text content of price to the coresponding value from the prices object select.addEventListener('change', () => { price.textContent = prices[select.value]; }); </script> <button class="add-cart">Add To Cart <i class='bx bx-cart-add add-cart'></i></button> <h4>Product Details</h4> <span>Lil Tjay x Trap Type Beat - "Enjoy" in key D# Minor and 160 BPM,It has vibe of Lil Tjay , Pop Smoke and more , Prices are great for this type of beat;Tagged Mastered MP3 for $25,$27 for Tagged Unmastered Wav,$30 for Untagged unmastered Wav,$70 for Stems and $120 for Exlusive</span> </div> <div id="audio"> <audio controls style="width:100%;" id="audio-clip"> <source src="Audio/Enjoy 160 x D sharp minor.mp3" type="audio/mp3"> </audio> </div> </section> <script> // ADD IMAGE AND AUDIO AND ADD + TO OPEN AND CLOSE BOX! GREAT JOB-FOR WORKING WITH HEADACHE const addToCartButton = document.querySelector('.add-cart'); if (addToCartButton) { addToCartButton.addEventListener('click', () => { const productTitle = document.querySelector('#title').textContent; const productPrice = document.querySelector('#price').textContent; const selectedLicense = document.querySelector('#select').value; const cartItem = { title: productTitle, price: productPrice, license: selectedLicense }; localStorage.setItem('cartItem', JSON.stringify(cartItem)); }); } </script>
结算页代码
<h2 style="text-align:center;">Checkout</h2> <div id="cart-items"> <p style="text-align:center;">YOU ADDED THIS PRODUCTS</p> <hr /> <div class="product-container"> <button class="toggle-button"><span id="t-name"></span> <span id="t-price"></span> +</button> <div class="cart-items"></div> </div> </div> <div class="total"> <h3 style="text-align:center;">Tax: <br><span id="tax"></span></h3> <h3 style="text-align:center;">Subtotal: <br><span id="subtotal"></span></h3> <h3 style="text-align:center;">Total: <br><span id="total"></span></h3> <a href="http://localhost:4242"><button style="display:block;">Continue to payment</button></a> </div> <script> const cartItemsDiv = document.querySelector('.cart-items'); const storedCartItem = localStorage.getItem('cartItem'); const taxRate = 0.10; // 10% tax rate if (storedCartItem) { const cartItem = JSON.parse(storedCartItem); const cartItemElement = document.createElement('div'); cartItemElement.innerHTML = ` <h3>${cartItem.title}</h3> <p>Price: ${cartItem.price}</p> <p>License: ${cartItem.license}</p> `; cartItemsDiv.appendChild(cartItemElement); // Parse price as a number and remove dollar sign const price = Number(cartItem.price.replace('$', '')); const subtotal = document.querySelector('#subtotal'); subtotal.textContent = `$${price}`; const tax = document.querySelector('#tax'); tax.textContent = `$${(price * taxRate).toFixed(2)}`; const total = document.querySelector('#total'); total.textContent = `$${(price + (price * taxRate)).toFixed(2)}`; } </script>
问题原因与修复方案
问题根源
当前代码使用localStorage.setItem('cartItem', ...)每次添加商品时都会覆盖之前存储的单个商品对象,而非累加商品;结算页也仅读取单个商品数据,因此只能显示最后添加的商品。
修复步骤
1. 修改商品页的添加购物车逻辑
将单个商品存储改为数组存储,添加商品时先读取现有购物车数组,再追加新商品,最后存回localStorage:
const addToCartButton = document.querySelector('.add-cart'); if (addToCartButton) { addToCartButton.addEventListener('click', () => { const productTitle = document.querySelector('#title').textContent; const productPrice = document.querySelector('#price').textContent; const selectedLicense = document.querySelector('#select').value; const cartItem = { title: productTitle, price: productPrice, license: selectedLicense }; // 读取现有购物车数组,为空则初始化空数组 let cartItems = JSON.parse(localStorage.getItem('cartItems')) || []; // 添加新商品到数组 cartItems.push(cartItem); // 存回localStorage localStorage.setItem('cartItems', JSON.stringify(cartItems)); }); }
2. 修改结算页的读取与渲染逻辑
读取购物车数组,遍历渲染所有商品,并计算总金额:
const cartItemsDiv = document.querySelector('.cart-items'); const storedCartItems = localStorage.getItem('cartItems'); const taxRate = 0.10; // 10% tax rate if (storedCartItems) { const cartItems = JSON.parse(storedCartItems); let totalSubtotal = 0; // 遍历所有商品渲染 cartItems.forEach(cartItem => { const cartItemElement = document.createElement('div'); cartItemElement.innerHTML = ` <h3>${cartItem.title}</h3> <p>Price: ${cartItem.price}</p> <p>License: ${cartItem.license}</p> `; cartItemsDiv.appendChild(cartItemElement); // 累加商品价格到小计 const price = Number(cartItem.price.replace('$', '')); totalSubtotal += price; }); // 更新小计、税费和总金额 const subtotal = document.querySelector('#subtotal'); subtotal.textContent = `$${totalSubtotal.toFixed(2)}`; const taxAmount = totalSubtotal * taxRate; const tax = document.querySelector('#tax'); tax.textContent = `$${taxAmount.toFixed(2)}`; const total = document.querySelector('#total'); total.textContent = `$${(totalSubtotal + taxAmount).toFixed(2)}`; }
内容的提问来源于stack exchange,提问作者Danijel Krnic
相关产品推荐
相关产品推荐

