JavaScript购物车的实现通常涉及以下几个基础概念:
localStorage或sessionStorage来保存购物车数据,以便在页面刷新后仍然可以保留数据。以下是一个简单的JavaScript购物车实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车示例</title>
</head>
<body>
<div id="products">
<div class="product">
<span>商品1 - ¥100</span>
<button onclick="addToCart('商品1', 100)">添加到购物车</button>
</div>
<div class="product">
<span>商品2 - ¥200</span>
<button onclick="addToCart('商品2', 200)">添加到购物车</button>
</div>
</div>
<div id="cart">
<h2>购物车</h2>
<ul id="cartItems"></ul>
<p>总价: ¥<span id="totalPrice">0</span></p>
</div>
<script>
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function updateCartDisplay() {
const cartItems = document.getElementById('cartItems');
const totalPrice = document.getElementById('totalPrice');
cartItems.innerHTML = '';
let total = 0;
cart.forEach(item => {
const li = document.createElement('li');
li.textContent = `${item.name} - ¥${item.price}`;
const removeButton = document.createElement('button');
removeButton.textContent = '删除';
removeButton.onclick = () => removeFromCart(item.name);
li.appendChild(removeButton);
cartItems.appendChild(li);
total += item.price;
});
totalPrice.textContent = total;
localStorage.setItem('cart', JSON.stringify(cart));
}
function addToCart(name, price) {
const item = { name, price };
cart.push(item);
updateCartDisplay();
}
function removeFromCart(name) {
cart = cart.filter(item => item.name !== name);
updateCartDisplay();
}
updateCartDisplay();
</script>
</body>
</html>通过以上步骤和示例代码,可以实现一个基本的JavaScript购物车功能,并根据具体需求进行扩展和优化。
没有搜到相关的沙龙