function add(items) {
const tbody = select('tbody')[0];
for(let i = 0; i < items.length;i++) {
tbody.innerHTML += `<tr>
<td>${items[i].name}</td>
<td>${(items[i].price * 1).toFixed(2)}</td>
<td><a href="javascript:void(0);">删除</a></td>
</tr>`
}
renderTotal();
bind();
}
function bind() {
const tbody = select('tbody')[0];
const trList = select('tr',tbody);
const aList = select('a',tbody);
tbody.addEventListener('click',function(e) {
let t = e.target;
if(t.tagName == 'A') {
tbody.removeChild(trList[aList.indexOf(t)]);
renderTotal();
}
})
}
function renderTotal() {
const tbody = select('tbody')[0];
const tfoot = select('tfoot')[0];
const totalNode = select('td',tfoot)[0];
const trList = select('tr',tbody);
const sum = trList.reduce((total,tr) => total + tr.children[1].innerText * 1,0);
totalNode.innerHTML = `${sum.toFixed(2)}(${trList.length}件商品)`;
}
function select(name,el = null) {
if(!el) {
return [].slice.call(document.getElementsByTagName(name),0)
};
return [].slice.call(el.getElementsByTagName(name),0);
}
add([{name: '产品',price: 66}]);