题解 | #购物车#
购物车
https://www.nowcoder.com/practice/3b4a342351ce483e813e5588446fc1f8
function add(items) { let tbody = document.getElementsByTagName('tbody')[0]; let content = ''; items.forEach(item => { content += `<tr><td>${item.name}</td><td>${item.price.toFixed(2)}</td><td><a href="javascript:void(0);">删除</a></td></tr>` }); tbody.innerHTML += content; this.getAmount(); } function bind() { let that = this; let tbody = document.getElementsByTagName('tbody')[0]; tbody.addEventListener('click', function (e) { if (e.target.nodeName === 'A') { e.target.parentElement.parentElement.remove(); that.getAmount(); } }); } function getAmount() { let tbody = document.getElementsByTagName('tbody')[0]; let all = tbody.getElementsByTagName('tr'); let tfoot = document.getElementsByTagName('tfoot')[0]; let amount = tfoot.getElementsByTagName('tr')[0].getElementsByTagName('td')[0]; let res = Array.from(all).reduce((tmp, item) => tmp + Number(item.children[1].innerHTML), 0); amount.innerHTML = `${res.toFixed(2)}(${all.length}件商品)` } this.bind();邪门,金额总计我用汇总就能在牛客跑通,换成for...of金额想家啊就过不去
#建议牛客在专项练习上进行改进#