题解 | #购物车#

购物车

https://www.nowcoder.com/practice/3b4a342351ce483e813e5588446fc1f8

简洁、易读
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();
        }
    })
}


全部评论

相关推荐

06-26 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
醉蟀:你不干有的是人干
点赞 评论 收藏
分享
06-27 15:29
门头沟学院 Java
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务