如何实现JavaScript数据在HTML中展示?购物车代码问题求助
Hey Trevor, let's walk through fixing your shopping cart code step by step—there are a few syntax issues, mismatched property names, and DOM-related problems that are keeping it from working as expected.
Key Issues in Your Original Code
- Mismatched Property Name: In
product_table(), you tried to accessproducts[i].product_name, but your product objects useproduct_id(set inproduct_setup()). That's why product names weren't showing up. - Broken String Concatenation for Buttons: The button HTML in your product table wasn't properly wrapped in quotes, causing a syntax error. You need to escape quotes correctly when building the HTML string.
- Missing DOM Elements: Your HTML body was cut off, and there were no elements with IDs
location1,location2,location3—soinnerHTMLhad nowhere to render the tables. - Script Placement: Running
product_table()andrenderCartTable()in the<head>means the DOM isn't fully loaded yet, so the script can't find the target elements. - Syntax Error in Script Tag: You had an extra comma in
<script type = "text/javascript", language = "javascript">—remove that comma. - Mismatched Function Parameters: The
addCart()function expects aproduct_id, but your button onclick was passing a non-existentproduct_namevalue.
Fixed Full Code
<!DOCTYPE html> <html> <head> <title>ACME Corp Shopping Cart</title> <link rel="stylesheet" href="shopstyle.css"> </head> <body> <h2>Available Products</h2> <div id="location1"></div> <h2>Your Cart</h2> <div id="location2"></div> <h3>Grand Total: $<span id="location3">0.00</span></h3> <script type="text/javascript"> alert("YAS"); var products = []; var cart = []; // Define products var product1 = ["Anvil", "Premium Grade Iron", 119.99]; var product2 = ["Female Roadrunner Costume", "Guaranteed to attract Male Roadrunners", 54.99]; function product_setup(product){ var productID = product[0]; var product_desc = product[1]; var qty = 1; var price = product[2]; var newProduct = { product_id: null, product_desc: null, product_qty: 0, product_price: 0.00, }; newProduct.product_id = productID; newProduct.product_desc = product_desc; newProduct.product_qty = qty; newProduct.product_price = price; products.push(newProduct); } product_setup(product1); product_setup(product2); function product_table() { var html = "<table border='1'>"; // Add proper header row html += "<tr>"; html += "<td>Product Name</td>"; html += "<td>Product Description</td>"; html += "<td>Price</td>"; html += "<td>Add to Cart</td>"; html += "</tr>"; for (var i = 0; i < products.length; i ++) { html += "<tr>"; html += "<td>" + products[i].product_id + "</td>"; // Fixed property name html += "<td>" + products[i].product_desc + "</td>"; html += "<td>$" + products[i].product_price.toFixed(2) + "</td>"; // Format price // Fixed button string with escaped quotes html += "<td><button type='button' onclick='addCart(\"" + products[i].product_id + "\")'>Add to Cart</button></td>"; html += "</tr>"; } html += "</table>"; document.getElementById("location1").innerHTML = html; } function addCart(product_id) { for (var i = 0; i < products.length; i++) { if (products[i].product_id == product_id) { var cartItem = null; for (var k = 0; k < cart.length; k++) { if (cart[k].product.product_id == products[i].product_id) { cartItem = cart[k]; cart[k].product_qty++; break; } } if (cartItem == null) { cartItem = { product: products[i], product_qty: products[i].product_qty }; cart.push(cartItem); } } } renderCartTable(); } function subtractQuantity(product_id) { for (var i = 0; i < cart.length; i++) { if (cart[i].product.product_id == product_id) { cart[i].product_qty--; if (cart[i].product_qty == 0) { cart.splice(i,1); i--; // Adjust index to avoid skipping items after splice } break; } } renderCartTable(); } function addQuantity(product_id) { for (var i = 0; i < cart.length; i++) { if (cart[i].product.product_id == product_id) { cart[i].product_qty++; break; } } renderCartTable(); } function removeItem(product_id) { for (var i = 0; i < cart.length; i++) { if (cart[i].product.product_id == product_id) { cart.splice(i,1); i--; // Adjust index after splice break; } } renderCartTable(); } function renderCartTable() { var html = ''; var ele = document.getElementById("location2"); ele.innerHTML = ''; html += "<table id='tblCart' border='1'>"; html += "<tr><td>Product ID</td>"; html += "<td>Product Description</td>"; html += "<td>Quantity</td>"; html += "<td>Price</td>"; html += "<td>Total</td>"; html += "<td>Action</td></tr>"; var GrandTotal = 0; for (var i = 0; i < cart.length; i++) { var itemTotal = parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10); GrandTotal += itemTotal; html += "<tr>"; html += "<td>" + cart[i].product.product_id + "</td>"; html += "<td>" + cart[i].product.product_desc + "</td>"; html += "<td>" + cart[i].product_qty + "</td>"; html += "<td>$" + cart[i].product.product_price.toFixed(2) + "</td>"; html += "<td>$" + itemTotal.toFixed(2) + "</td>"; // Fixed button onclick quotes html += "<td>"; html += "<button type='button' onClick='subtractQuantity(\"" + cart[i].product.product_id + "\")'>Subtract Item</button> "; html += "<button type='button' onClick='addQuantity(\"" + cart[i].product.product_id + "\")'>Add Item</button> "; html += "<button type='button' onClick='removeItem(\"" + cart[i].product.product_id + "\")'>Remove Item</button>"; html += "</td>"; html += "</tr>"; } html += "</table>"; ele.innerHTML = html; // Format grand total to 2 decimal places document.getElementById("location3").innerHTML = GrandTotal.toFixed(2); } // Run functions after DOM is fully loaded document.addEventListener('DOMContentLoaded', function() { product_table(); renderCartTable(); }); </script> </body> </html>
Additional Improvements Made
- Added proper table header rows (you forgot wrapping
<tr>tags around your header cells originally) - Formatted all prices to 2 decimal places for consistency
- Fixed the
subtractQuantityfunction to adjust the loop index after splicing an item (prevents skipping the next item) - Changed button types from
submittobutton(since we're not submitting a form) - Wrapped initial function calls in
DOMContentLoadedto ensure the DOM is ready before rendering
内容的提问来源于stack exchange,提问作者Trevor Stammler
相关产品推荐
相关产品推荐

