1.效果图
2.代码实现
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table cellspacing="0" border="1" cellpadding="0" style="text-align: center;">
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品商品单价</th>
<th>商品数量</th>
<th>小计金额</th>
</tr>
<tr>
<td>001</td>
<td>Apple iPone 13</td>
<td>5999</td>
<td><button class="btn_sub" >-</button>0<button class="btn_sum">+</button></td>
<td>0</td>
</tr>
<tr>
<td>002</td>
<td>Apple iPone 13 钢化膜</td>
<td>199</td>
<td><button class="btn_sub">-</button>0<button class="btn_sum">+</button></td>
<td>0</td>
</tr>
<tr>
<td>003</td>
<td>Apple iPone 13 充电器</td>
<td>259</td>
<td><button class="btn_sub">-</button>0<button class="btn_sum">+</button></td>
<td>0</td>
</tr>
<tr>
<td colspan="4" >总金额<span>0</span>元</td>
<td><button id="total">立即结算</button></td>
</tr>
</table>
<script src="./js/index.js"></script>
</body>
</html
index.js
let btn_sum = document.getElementsByClassName(`btn_sum`)
let btn_sub = document.getElementsByClassName(`btn_sub`)
let btn_totle = document.getElementById(`total`)
//声明变量 用于计算总数
let totle = 0
//给结算按钮添加事件
btn_totle.onclick = () => {
alert(`共消费${totle}元`)
//刷新页面
this.location.reload()
}
// 声明方法,分别给数量增加按钮和数量减少按钮添加事件
// this:指触发当前事件的对象(源对象),
// parentNode:当前对象的父级对象,
// childNodes:当前对象的子级对象的集合,
// textContent:当前对象的文本内容(字符串)
let btn_sum_f = () => {
//遍历数组
for (let v of btn_sum) {
//这里注意不能用箭头函数,箭头函数this不会随调用环境变化而变化,this会一直指向调用这个方法的环境,也就是window。所以这里用普通函数function()声明
v.onclick = function () {
//计算当前行的商品数量+1,并显示到前端页面
this.parentNode.childNodes[1].textContent = parseInt(this.parentNode.childNodes[1].textContent) + 1
//计算当前行的小计金额=商品数量*商品单价,并显示到前端页面
this.parentNode.parentNode.childNodes[9].textContent =
parseInt(this.parentNode.parentNode.childNodes[5].textContent) *
parseInt(this.parentNode.childNodes[1].textContent)
// 累加当前总价
totle = parseInt(this.parentNode.parentNode.childNodes[9].textContent) + totle
//将当前总金额显示到前端页面
this.parentNode.parentNode.parentNode.childNodes[8].childNodes[1].childNodes[1].textContent = totle
}
}
for (let v of btn_sub) {
//这里注意不能用箭头函数,箭头函数this不会随调用环境变化而变化
//this会一直指向调用这个方法的环境,也就是window。所以这里用普通函数function()声明
v.onclick = function () {
//判断如果商品数量为零就不能向下减,返回不继续执行下面的流程
if (this.parentNode.childNodes[1].textContent == 0) return
//计算当前行的商品数量-1,并显示到前端页面
this.parentNode.childNodes[1].textContent = parseInt(this.parentNode.childNodes[1].textContent) - 1
//累减当前总价,这里需要先减再执行下面的小计金额计算
totle = totle - parseInt(this.parentNode.parentNode.childNodes[9].textContent)
//将当前总金额显示到前端页面
this.parentNode.parentNode.parentNode.childNodes[8].childNodes[1].childNodes[1].textContent = totle
//计算当前行的小计金额=商品数量*商品单价,并显示到前端页面
this.parentNode.parentNode.childNodes[9].textContent =
parseInt(this.parentNode.parentNode.childNodes[5].textContent) *
parseInt(this.parentNode.childNodes[1].textContent)
}
}
}
//调用方法
btn_sum_f()