简洁、易读
1. 封装一个公共函数用来计算total和渲染
2. add考察createElement 和appendChild
3. bind考察事件冒泡机制, 为tbody添加click事件
4. 注意保留两位小数
function resetTotal() {
const prices = [];
const trs = Array.from(document.querySelectorAll('tbody tr'));
for (let tr of trs) {
let td = tr.children[1];
let price = parseFloat(td.innerText);
prices.push(price);
}
const tTotal = document.querySelector('tfoot tr td');
const total = prices.reduce((a, b) => a + b, 0);
tTotal.innerHTML = `${total.toFixed(2)}(${prices.length}件商品)`;
}
function add(items) {
const tbody = document.querySelector('tbody');
for (let item of items) {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${item.name}</td><td>${item.price.toFixed(2)}</td><td><a href="javascript:void(0);">删除</a></td>`;
tbody.appendChild(tr);
}
resetTotal();
}
function bind() {
const tbody = document.querySelector('tbody');
tbody.addEventListener('click', (e) => {
if (e.target.tagName === 'A') {
const tr = e.target.parentNode.parentNode;
tbody.removeChild(tr);
resetTotal();
}
})
}



京公网安备 11010502036488号