看到网上的购物车案例要不是用框架、要不就是用jQuery,自己用原生JS实现,可以添加任意多件商品,避免多次获取DOM对象:
首先是HTML+CSS部分:
<!DOCTYPE html>
<html>
<head>
<title>购物车</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #333;
text-align: center;
}
table {
width: 100%;
border-collapse: collapse;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
th, td {
padding: 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #4CAF50;
color: white;
}
tr:hover {
background-color: #f5f5f5;
}
.subtotal, .total {
font-weight: bold;
}
input[type="number"] {
width: 50px;
}
</style>
</head>
<body>
<h1>购物车</h1>
<div>
<table>
<thead>
<tr>
<th><input type="checkbox" id="selectAll"></th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="select"></td>
<td>商品A</td>
<td class="price">100.00</td>
<td><input type="number" class="quantity" value="0" min="0"></td>
<td class="subtotal">0</td>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>商品B</td>
<td class="price">200.00</td>
<td><input type="number" class="quantity" value="0" min="0"></td>
<td class="subtotal">0</td>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>商品C</td>
<td class="price">300.00</td>
<td><input type="number" class="quantity" value="0" min="0"></td>
<td class="subtotal">0</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" style="text-align: right;">总计:</td>
<td class="total" id="sum">0</td>
</tr>
</tfoot>
</table>
</div>
<script src="index.js"></script>
</body>
</html>
然后是JS部分:
var allbutton = document.querySelector("#selectAll");
var totalprice = document.querySelector("#sum");
var select = document.querySelectorAll(".select");
allbutton.addEventListener("change", () => {
for (var i = 0; i < select.length; i++) {
select[i].checked = allbutton.checked;
}
sumprice();
});
select.forEach(ele => {
ele.addEventListener("change", () => {
if (ele.checked == false) {
allbutton.checked = false;
}
sumprice();
allSel();
});
});
function allSel() {
var count = 0;
for (var i = 0; i < select.length; i++) {
if (select[i].checked) {
count++;
}
}
if (count == select.length) {
allbutton.checked = true;
}
}
select.forEach(item => {
item.parentNode.nextElementSibling.nextElementSibling.nextElementSibling.lastChild.addEventListener(
"change",
() => {
item.parentNode.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML =
subcount(
item.parentNode.nextElementSibling.nextElementSibling,
item.parentNode.nextElementSibling.nextElementSibling
.nextElementSibling.lastChild
);
sumprice();
}
);
});
function subcount(price, count) {
return (parseFloat(price.innerHTML) * count.value).toFixed(2);
}
function sumprice() {
var sum = 0;
select.forEach(i => {
if (i.checked) {
sum += parseFloat(
i.parentNode.parentNode.lastChild.previousSibling.innerHTML
);
}
});
totalprice.innerHTML = sum.toFixed(2);
}