如何在不硬编码的情况下实现商品图片与音频跨页面传递展示
问题需求
我在Stack Overflow社区的帮助下,已实现购物车中已添加商品的展示功能。现需优化:不使用硬编码的前提下,将商品页面的商品图片与音频信息传递至结账页面,并在结账页正确展示。
现有代码
商品页代码
<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> var selectedItems = []; 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, }; selectedItems.push(cartItem); console.log(selectedItems); localStorage.setItem('selectedItems', JSON.stringify(selectedItems)); }); } </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"> <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> <a href="http://localhost:4242"><button style="display:block; background-color: rgb(216, 4, 4);">Cancel</button></a> <!--Make next to eachself and red and blue color for button--> </div> <script> const cartItemsDiv = document.querySelector(".cart-items"); const storedCartItem = localStorage.getItem("selectedItems"); const taxRate = 0.1; // 10% tax rate let subtotal = 0; if (storedCartItem) { const cartItem = JSON.parse(storedCartItem); // Parse the storedCartItem string into an array for (let i = 0; i < cartItem.length; i++) { const cartItemElement = document.createElement("div"); cartItemElement.innerHTML = ` <h3>${cartItem[i].title}</h3> <p>Price: ${cartItem[i].price}</p> <p>License: ${cartItem[i].license}</p> `; cartItemsDiv.appendChild(cartItemElement); const price = Number(cartItem[i].price.replace("$", "")); // Parse price as a number and remove dollar sign subtotal += price; } const subtotalElement = document.querySelector("#subtotal"); subtotalElement.textContent = `$${subtotal.toFixed(2)}`; const taxElement = document.querySelector("#tax"); const tax = subtotal * taxRate; taxElement.textContent = `$${tax.toFixed(2)}`; const totalElement = document.querySelector("#total"); const total = subtotal + tax; totalElement.textContent = `$${total.toFixed(2)}`; } </script>
解决方案
步骤1:修改商品页的购物车存储逻辑
在添加商品到购物车时,动态获取图片和音频的URL并存入localStorage,替换商品页底部的<script>代码:
var selectedItems = []; 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; // 动态获取商品图片URL const productImage = document.querySelector('#product-image').src; // 动态获取音频文件URL const productAudio = document.querySelector('#audio-clip source').src; const cartItem = { title: productTitle, price: productPrice, license: selectedLicense, image: productImage, audio: productAudio }; selectedItems.push(cartItem); console.log(selectedItems); localStorage.setItem('selectedItems', JSON.stringify(selectedItems)); }); }
步骤2:修改结账页的商品渲染逻辑
在结账页渲染商品时,添加图片和音频的展示结构,替换结账页底部的<script>代码:
const cartItemsDiv = document.querySelector(".cart-items"); const storedCartItem = localStorage.getItem("selectedItems"); const taxRate = 0.1; // 10% tax rate let subtotal = 0; if (storedCartItem) { const cartItems = JSON.parse(storedCartItem); for (let i = 0; i < cartItems.length; i++) { const cartItemElement = document.createElement("div"); // 加入图片和音频的展示HTML cartItemElement.innerHTML = ` <div style="display: flex; gap: 20px; margin-bottom: 20px; align-items: center;"> <img src="${cartItems[i].image}" alt="${cartItems[i].title}" style="width: 100px; height: auto;"> <div> <h3>${cartItems[i].title}</h3> <p>Price: ${cartItems[i].price}</p> <p>License: ${cartItems[i].license}</p> <audio controls style="width: 200px;"> <source src="${cartItems[i].audio}" type="audio/mp3"> </audio> </div> </div> <hr> `; cartItemsDiv.appendChild(cartItemElement); const price = Number(cartItems[i].price.replace("$", "")); subtotal += price; } const subtotalElement = document.querySelector("#subtotal"); subtotalElement.textContent = `$${subtotal.toFixed(2)}`; const taxElement = document.querySelector("#tax"); const tax = subtotal * taxRate; taxElement.textContent = `$${tax.toFixed(2)}`; const totalElement = document.querySelector("#total"); const total = subtotal + tax; totalElement.textContent = `$${total.toFixed(2)}`; }
核心说明
- 通过DOM选择器动态获取资源URL,完全避免硬编码,适配不同商品页面的路径
- 结账页使用flex布局优化排版,让图片与商品信息横向对齐,音频控件设置固定宽度保证页面整洁
- 所有数据通过localStorage本地传递,无需依赖后端服务或URL参数
内容的提问来源于stack exchange,提问作者Danijel Krnic
相关产品推荐
相关产品推荐

