jQuery 是一个快速、简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。使用 jQuery 实现购物车功能,通常涉及到以下几个方面:
以下是一个简单的静态购物车实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="products">
<div class="product">
<span>商品A - ¥10</span>
<button class="add-to-cart" data-name="商品A" data-price="10">加入购物车</button>
</div>
<div class="product">
<span>商品B - ¥20</span>
<button class="add-to-cart" data-name="商品B" data-price="20">加入购物车</button>
</div>
</div>
<div id="cart">
<h3>购物车</h3>
<ul id="cart-items"></ul>
<p>总价: <span id="total-price">0</span></p>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
#cart {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
$(document).ready(function() {
var cart = [];
$('.add-to-cart').click(function() {
var name = $(this).data('name');
var price = parseInt($(this).data('price'));
var item = {name: name, price: price, quantity: 1};
var existingItem = cart.find(function(i) { return i.name === name; });
if (existingItem) {
existingItem.quantity++;
} else {
cart.push(item);
}
updateCartDisplay();
});
function updateCartDisplay() {
$('#cart-items').empty();
var totalPrice = 0;
cart.forEach(function(item) {
var listItem = $('<li></li>').text(item.name + ' x ' + item.quantity + ' - ¥' + (item.price * item.quantity));
$('#cart-items').append(listItem);
totalPrice += item.price * item.quantity;
});
$('#total-price').text(totalPrice);
}
});
updateCartDisplay
函数来刷新购物车显示。通过以上步骤和代码示例,你可以实现一个基本的购物车功能。如果需要更复杂的功能(如与服务器同步、用户登录状态管理等),则需要进一步扩展和后端交互。
领取专属 10元无门槛券
手把手带您无忧上云