<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>实现购物车的相关功能</title>
<style>
*{
margin:0;
padding:0;
}
table{
width: 600px;
border-collapse: collapse;
}
th,td{
border:1px solid #000;
width: 150px;
/*padding:5px 40px;*/
text-align: center;
}
#chart{
width: 800px;
margin:100px auto;
}
button{
width: 20px;
height: 20px;
}
thead{
background-color: aquamarine;
}
tfoot{
background-color: transparent;
}
</style>
</head>
<body>
<div id="chart">
<table>
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr>
<td>iPhone6</td>
<td>¥4488</td>
<td>
<button onclick="calc(this)">-</button>
<span>0</span>
<button onclick="calc(this)">+</button>
</td>
<td>
</td>
</tr>
<tr>
<td>iPhone7</td>
<td>¥7488</td>
<td>
<button onclick="calc(this)">-</button>
<span>0</span>
<button onclick="calc(this)">+</button>
</td>
<td>
</td>
</tr>
<tr>
<td>iPhone8</td>
<td>¥8488</td>
<td>
<button onclick="calc(this)">-</button>
<span>0</span>
<button onclick="calc(this)">+</button>
</td>
<td>
</td>
</tr>
<tr>
<td>iPhoneX</td>
<td>¥9488</td>
<td>
<button onclick="calc(this)">-</button>
<span>0</span>
<button onclick="calc(this)">+</button>
</td>
<td>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right">Total</td>
<td>0.00</td>
</tr>
</tfoot>
</table>
</div>
<script src="js/jquery-3.2.1.min.js"></script>
<script>
// 创建函数 calc
function calc(btn) {
// 第一步:修改数量
// 获得btn的父节点保存在变量td中
var td=btn.parentNode;
console.log(td);
// 获取td下的唯一一个span元素,保存在变量span中
var span=td.querySelector("span");
console.log(span);
// 获得span的内容,保存在变量n中,并转化其string形式为number形式
var n=parseInt(span.innerHTML);
console.log(typeof(n));
// 判断:如果btn是+,就+1;否则,如果已经是1,就为0,否则就—1;
n+=btn.innerHTML=="+"?1:n==0?0:-1;
// 设置span的内容为n
span.innerHTML=n;
// 计算小计
//获得td的前一个兄弟元素的内容,从?位截取,转为浮点数后,保存在变量price中
var price=parseFloat(td.previousElementSibling.innerHTML.slice(1));
console.log(typeof (price));
// 设置td的后一个兄弟元素的内容为"¥"+price*n,要求小计要按2位小数四舍五入
var total=td.nextElementSibling.innerHTML="¥"+price*n.toFixed(2);
// 计算总和
// 获得id为chart下的tbody下的每个tr下的最后一个td,保存在变量tds中
var data=document.getElementById("chart");
console.log(data);
var tds=data.querySelectorAll("tbody>tr>td:last-child");
console.log(tds);
for(var i=0,sum=0;i<tds.length;i++){
// 遍历tds中每一个td,同时声明变量sum为0
sum+=parseFloat(tds[i].innerHTML.slice(1));
}//遍历结束
// 设置id为chart下的tfoot下的tr下的最后一个td的内容为:
// "¥"+sum.toFixed(2);
data.querySelector("tfoot>tr>td:last-child").innerHTML="¥"+sum.toFixed(2);
}
</script>
</body>
</html>
原生js实现购物车相关功能
猜你喜欢
转载自blog.csdn.net/yingleiming/article/details/79974716
今日推荐
周排行