原生js(效果图如下):
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ceb0b9052140a57fb99b886084c96a81.png)
代码(html、css、js没有分离):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.tab{
width: 500px;
height: 100px;
border-collapse: collapse;
margin: 0 auto;
}
.tab td,th{
border: 1px solid #000;
}
</style>
</head>
<body>
<table class="tab">
<thead>
<th><button type="button" class="all">全选</button>
<button type="button" class="noAll">全不选</button>
</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="ed"/></td>
<td>电脑</td>
<td class="price">200</td>
<td>
<button type="button" class="sub">-</button>
<span>1</span>
<button type="button" class="add">+</button>
</td>
<td class="small_total">200</td>
<td>删除</td>
</tr>
<tr>
<td><input type="checkbox" class="ed"/></td>
<td>手机</td>
<td class="price">100</td>
<td>
<button type="button" class="sub">-</button>
<span>1</span>
<button type="button" class="add">+</button>
</td>
<td class="small_total">100</td>
<td>删除</td>
</tr>
</tbody>
</table>
<div>
<span>总计:</span>
<span class="sum">0</span>
</div>
</body>
<script type="text/javascript">
var tab = document.querySelector('.tab');
var add = tab.querySelectorAll('.add');
var sub = tab.querySelectorAll('.sub');
var all = tab.querySelector('.all');
var noAll = tab.querySelector('.noAll');
var sum_total = document.querySelector('.sum');
var small_total = tab.querySelectorAll('.small_total');
var ed = tab.querySelectorAll('.ed');
getSum();
add.forEach(function(val,index){
add[index].addEventListener('click',function(){
var num = parseInt(this.previousElementSibling.innerHTML);
num++;
this.previousElementSibling.innerHTML = num;
var price = parseInt(this.parentNode.previousElementSibling.innerHTML);
this.parentNode.nextElementSibling.innerHTML = price*num;
getSum();
})
})
sub.forEach(function(val,index){
sub[index].addEventListener('click',function(){
var num = parseInt(this.nextElementSibling.innerHTML);
num--;
if(num<1) num=1;
this.nextElementSibling.innerHTML = num;
var price = parseInt(this.parentNode.previousElementSibling.innerHTML);
this.parentNode.nextElementSibling.innerHTML = price*num;
getSum();
})
})
function getSum(){
var sum = 0;
for(var i = 0;i<small_total.length;i++){
if(small_total[i].parentNode.children[0].children[0].checked){
sum += parseInt(small_total[i].innerHTML);
}
}
sum_total.innerHTML = sum;
}
all.addEventListener('click',function(){
ed.forEach(function(val,index){
ed[index].checked = 'checked';
})
getSum();
})
ed.forEach(function(val,index){
ed[index].onclick=function(){
getSum();
}
})
noAll.addEventListener('click',function(){
ed.forEach(function(val,index){
ed[index].checked = '';
})
getSum();
})
</script>
</html>