<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车</title>
<style>
table {
width: 600px;
border-collapse: collapse;
}
thead {
background-color: #eee;
}
td {
border: 1px solid gray;
text-align: center;
padding: 10px 20px;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td>商品信息</td>
<td>单价</td>
<td>数量</td>
<td>金额</td>
</tr>
</thead>
<tbody>
<tr>
<td>保暖棉服BF风</td>
<td>318.00</td>
<td>
<button disabled>-</button>
<span>1</span>
<button>+</button>
</td>
<td>318.00</td>
</tr>
<tr>
<td>安踏运动鞋</td>
<td>400.00</td>
<td>
<button>-</button>
<span>3</span>
<button>+</button>
</td>
<td>1200.00</td>
</tr>
<tr>
<td>GPW2代鼠标</td>
<td>1100.00</td>
<td>
<button>-</button>
<span>2</span>
<button>+</button>
</td>
<td>2200.00</td>
</tr>
<tr>
<td>iqoo10 pro 512</td>
<td>5999.00</td>
<td>
<button disabled>-</button>
<span>1</span>
<button>+</button>
</td>
<td>5999.00</td>
</tr>
<tr>
<td>奥特曼抽抽卡</td>
<td>120.00</td>
<td>
<button>-</button>
<span>4</span>
<button>+</button>
</td>
<td>480.00</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">
总金额:
<b>10197</b>
</td>
</tr>
</tfoot>
</table>
<script src="./vendor/jquery-3.6.0.js"></script>
<script>
// 封装技巧:
// 场景: 当一大段代码 需要重复使用时, 用函数封装起来-复用
// 更新金额
// 声明形参, 接收传递的实参
function updateSum(n) {
// 单价: 按钮的父元素的 上一个元素
// var $price = $(this).parent().prev()
// var sum = $price.html() * n
// console.log('sum:', sum)
// // 把sum设置给 金额元素中
// $(this).parent().next().html(sum.toFixed(2))
// 找到所有的金额, 遍历累加其中的值
console.log($('tbody td:last-child'))
// each: 遍历查询到的元素
// 参数1:元素序号 参数2:元素本身
// var total = 0
// $('tbody td:last-child').each((index, elem) => {
// console.log(index, elem)
// // elem: 原生的DOM对象, 需要$()转为JQ对象才能用JQ的方法
// var n = $(elem).html()
// // console.log(n)
// total -= -n
// })
// console.log('total:', total);
// // 更新到 总金额里
// $('tfoot b').html(total.toFixed(2))
updateTotal()
})
// 减:
$('table button:contains(-)').click(function () {
var $num = $(this).next()
var n = $num.html() - 1
$num.html(n)
if (n == 1) $(this).prop('disabled', true)
updateSum.call(this, n)
// 单价: 按钮的父元素的 上一个元素
// var $price = $(this).parent().prev()
// var sum = $price.html() * n
// console.log('sum:', sum)
// // 把sum设置给 金额元素中
// $(this).parent().next().html(sum.toFixed(2))
updateTotal()
})
</script>
</body>
</html>