HTML部分:
<困悔div class="cart-container">
<h2>购物车</h2>
<ul class="cart-items">
<li class="cart-item">
<img src="item1.jpg" alt="商品1">
<span class="item-name">商品1</span>
<span class="item-price">100元</span>
<input type="number" class="item-quantity" value="1"改尺枝>
<button class="remove-btn">删除</button>
</li>
<li class="cart-item">
<img src="item2.jpg" alt="商品2">
<span class="item-name">商品2</核敏span>
<span class="item-price">200元</span>
<input type="number" class="item-quantity" value="1">
<button class="remove-btn">删除</button>
</li>
</ul>
<p class="total-price">总价:<span>300元</span></p>
</div>
CSS部分:
.cart-container {
width: 400px
border: 1px solid #ccc
padding: 20px
}
.cart-items {
list-style-type: none
padding: 0
margin: 0
}
.cart-item {
display: flex
align-items: center
margin-bottom: 10px
}
.cart-item img {
width: 80px
height: 80px
margin-right: 10px
}
.item-name, .item-price {
flex: 1
}
.item-quantity {
width: 50px
margin-right: 10px
}
.remove-btn {
background-color: #ccc
border: none
padding: 5px 10px
cursor: pointer
}
.total-price {
margin-top: 20px
text-align: right
}
jQuery部分:
$(document).ready(function() {
// 计算初始总价
updateTotalPrice()
// 删除商品按钮点击事件
$('.remove-btn').click(function() {
$(this).parent().remove()
updateTotalPrice()
})
// 商品数量输入框变化事件
$('.item-quantity').change(function() {
updateTotalPrice()
})
// 更新总价函数
function updateTotalPrice() {
var total = 0
$('.cart-item').each(function() {
var price = parseInt($(this).find('.item-price').text())
var quantity = parseInt($(this).find('.item-quantity').val())
total += price * quantity
})
$('.total-price span').text(total + '元')
}
})
该示例中,使用了HTML和CSS来构建购物车的界面,使用jQuery来实现购物车的逻辑。购物车中的每个商品都包含了商品名称、商品图片、商品价格、商品数量和删除按钮,当点击删除按钮时,对应的商品会从购物车中删除并重新计算总价;当商品数量变化时,总价也会自动更新。
微信小程序的购物车功能在商品列表页
index.wxml
中,给下单按钮绑定一个添加购物车的事件
addCart
,使用
catchtap
是不会冒泡,同时传入
data-item
,当前的商品,代码如下所示:
1
<view class="order" catchtap="addCart" data-item="{{ item }}">下单</view>
在
index.js
中,在
Page
中,定义
addCart
事件。对此,可以分析一下当点击按钮以后添加购物车的逻辑:
拿到点击要添加入到购物车的商品
判断该商品在不在购物车里面
如果不在, 把该做腔念商品添加到购物车里面, 并且新加一个字段
num = 1
如果在,修改改商品的
num
值 累加
在
addCart
中,第一步拿到该商品,通过
e.currentTarget.dataset
获取。第二步,判断该商品在不在购物车里面,根据
_id
尝试从购物车里面获取数据,看能不能获纯困取的到。使用
try...catch
,在有值的情况下,把购圆雀物车里面的该商品的
num
值累加
,并且进行下单成功的提示;在没有值,把商品添加到购物车里面,并且进行下单成功的提示,最后调用
setTabBar()
方法修改底部购物车
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)