效果图
实现源码
1.首先先引入jq的cdn
2.源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>09_实现购物车动态操作</title>
<script src="../../code/JS/jq.js"></script>
<style>
table {
width: 600px;
text-align: center;
border-collapse: collapse;
}
td {
width: 100px;
}
td,
th {
border: 1px solid black
}
td[colspan="3"] {
text-align: right;
}
td span {
display: inline-block;
width: 20px;
}
</style>
</head>
<body>
<table id="data">
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr>
<td>iPhone6</td>
<td>¥<span>4488</span></td>
<td>
<button class="subtract">-</button>
<span>1</span>
<button class="plus">+</button>
</td>
<td>¥<span class="subtotal">4488</span></td>
</tr>
<tr>
<td>iPhone6 plus</td>
<td>¥<span>5288</span></td>
<td>
<button class="subtract">-</button>
<span>1</span>
<button class="plus">+</button>
</td>
<td>¥<span class="subtotal">5288</span></td>
</tr>
<tr>
<td>iPad Air 2</td>
<td>¥<span>4288</span></td>
<td>
<button class="subtract">-</button>
<span>1</span>
<button class="plus">+</button>
</td>
<td>¥<span class="subtotal">4288</span></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Total:</td>
<td>¥<span class="total">14064</span></td>
</tr>
</tfoot>
</table>
<script>
$('.plus').click(function () {
// console.log($(this).prev()[0]);
// $(this).prev()[0].innerText
// console.log($(this).prev().text());
// text() 设置元素的文本内容
// 设置数量的 自增
$(this).prev().text(Number($(this).prev().text()) + 1);
// 单价
// console.log($(this).parent().prev().children().text());
var price = $(this).parent().prev().children().text();
// 小计
// console.log($(this).parent().next().children().text());
$(this).parent().next().children().text(price * $(this).prev().text());
// $('.total').text();
// console.log();
var total = 0;
$('.subtotal').each(function (i, v) {
// console.log(v);
total += Number(v.innerText);
// console.log(total);
$('.total').text(total);
})
})
$('.subtract').click(function () {
if ($(this).next().text() <= 1) {
$(this).next().text(1);
} else {
// 让数量自减
$(this).next().text(Number($(this).next().text()) - 1)
// 单价
var price = $(this).parent().prev().children().text();
// 小计
$(this).parent().next().children().text(price * $(this).next().text());
// 记录总价
var total = 0;
$('.subtotal').each(function (i, v) {
// console.log(v);
total += Number(v.innerText);
// console.log(total);
$('.total').text(total);
})
}
})
</script>
</body>
</html>