jquery仿京东购物车
时间: 2024-01-11 08:04:35 浏览: 33
以下是使用jQuery仿京东购物车的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>jQuery仿京东购物车</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// 添加商品到购物车
$(".add-to-cart").click(function() {
var product = $(this).closest(".product");
var productName = product.find(".product-name").text();
var productPrice = product.find(".product-price").text();
var cartItem = $("<div class='cart-item'></div>");
cartItem.append("<span class='item-name'>" + productName + "</span>");
cartItem.append("<span class='item-price'>" + productPrice + "</span>");
$(".cart-items").append(cartItem);
});
// 从购物车中移除商品
$(document).on("click", ".remove-from-cart", function() {
$(this).closest(".cart-item").remove();
});
});
</script>
<style>
.product {
margin-bottom: 10px;
}
.cart-item {
margin-bottom: 5px;
}
</style>
</head>
<body>
<h1>商品列表</h1>
<div class="product">
<span class="product-name">商品1</span>
<span class="product-price">100元</span>
<button class="add-to-cart">加入购物车</button>
</div>
<div class="product">
<span class="product-name">商品2</span>
<span class="product-price">200元</span>
<button class="add-to-cart">加入购物车</button>
</div>
<h1>购物车</h1>
<div class="cart-items"></div>
</body>
</html>
```
这段代码实现了一个简单的购物车功能。当点击"加入购物车"按钮时,会将商品名称和价格添加到购物车中。购物车中的商品可以通过点击"移除"按钮来移除。