<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<style>
table,th,td{
border: 1px solid black;
}
table{
border-collapse: collapse;
margin-top: 30px;
margin-bottom: 30px;
width: 600px;
text-align: center;
}
td,th{
width: 120px;
}
button{
border: 0;
}
</style>
</head>
<body>
<table>
<tr>
<th><button class="all">全选</button></th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<tr>
<td>
<input type="checkbox" name="" class="getGoods">
</td>
<td>电脑</td>
<td class="price">200</td>
<td>
<button class="jian">-</button>
<span>1</span>
<button class="add">+</button></td>
<td class="total">200</td>
<td>删除</td>
</tr>
<tr>
<td><input type="checkbox" name="" class="getGoods"></td>
<td>手机</td>
<td class="price">100</td>
<td>
<button class="jian">-</button>
<span>1</span>
<button class="add">+</button>
</td>
<td class="total">100</td>
<td>删除</td>
</tr>
</table>
<div>
<span>总计:</span>
<span class="sum"> 0</span>
</div>
<script>
let flag = false;
$('.add').click(function () {
let num = parseInt($(this).prev().text());
num++;
$(this).prev().text(num)
let price = parseInt($(this).parent().prev().text());
$(this).parent().next().text(price * num);
getSum()
})
$('.jian').click(function () {
let sub = parseInt($(this).next().text());
sub--;
if(sub<1){
return
}
$(this).next().text(sub)
let price = parseInt($(this).parent().prev().text());
$(this).parent().next().text(price * sub);
getSum()
})
function getSum() {
let sum = 0;
for(let i = 0; i<$('.total').length; i++){
if($('.total').eq(i).parent().find('input').prop('checked')){
sum += parseInt($('.total').eq(i).text())
}
}
$('.sum').text(sum)
}
$('.all').click(function () {
$('.getGoods').prop('checked',true)
getSum()
})
$('.getGoods').click(function () {
getSum()
})
getSum()
</script>
</body>
</html>
?
?
|