實(shí)現(xiàn)購物車的代碼可以用各種編程語言編寫,以下是一個(gè)簡單的示例,這個(gè)簡單的購物車示例包括了HTML、CSS和JavaScript部分,使用了按鈕添加商品到購物車,展示了購物車中的商品列表以及總價(jià),并提供了結(jié)賬功能。
<!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Shopping Cart</title> <link rel=“stylesheet” href=“styles.css”> </head> <body> <div class=“cart”>
<h2>Shopping Cart</h2> <ul id="cart-items"></ul> <p>Total: $<span id="total-price">0</span></p> <button onclick="checkout()">Checkout</button>
</div>
<div class=“products”>
<h2>Products</h2> <ul id="product-list"> <li><button onclick="addItem('apple')">Add Apple</button></li> <li><button onclick="addItem('banana')">Add Banana</button></li> <li><button onclick="addItem('orange')">Add Orange</button></li> </ul>
</div>
<script src=“script.js”></script> </body> </html>
.cart, .products { float: left; margin-right: 20px; }
button { margin-top: 5px; }
.cart { width: 250px; }
.products { width: 200px; }
let cart = ; // 存儲(chǔ)購物車商品和數(shù)量的對(duì)象 let prices = ; // 商品價(jià)格
function addItem(item) { if (cart[item]) {
cart[item]++;
} else {
cart[item] = 1;
} updateCart(); }
function updateCart() { let cartItems = document.getElementById(‘cart-items’); cartItems.innerHTML = “; let totalPrice = 0;
for (let item in cart) {
let quantity = cart[item]; let price = prices[item]; let itemTotal = quantity * price; let li = document.createElement('li'); li.textContent = `$: $ x $$ = $$`; cartItems.appendChild(li); totalPrice += itemTotal;
}
document.getElementById(‘total-price’).textContent = totalPrice.toFixed(2); }
function checkout() { alert(‘Total cost of your purchase is: $’ + document.getElementById(‘total-price’).textContent); }