实现购物车的代码可以用各种编程语言编写,以下是一个简单的示例,这个简单的购物车示例包括了HTML、CSS和JavaScript部分,使用了按钮添加商品到购物车,展示了购物车中的商品列表以及总价,并提供了结账功能。
<!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 = ; // 存储购物车商品和数量的对象
let prices = ; // 商品价格
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);
}