批改状态:合格
老师批语:
// (一).导入购物车模块,获取data,total,totalMoney等数据import carts from './carts.js'// console.log(carts.total,carts.totalMoney);//(二).获取dom元素const total = document.querySelector('.total')const totalMoney = document.querySelector('.totalMoney')const items = document.querySelectorAll('.carts-body > .item')// console.log(items);// console.log(nums);//(三).渲染total.textContent = carts.totaltotalMoney.textContent = carts.totalMoney// 循环渲染购物车的每个元素items.forEach(function(item,index,arr){item.querySelector('.id').textContent = carts.data[index].iditem.querySelector('.name').textContent = carts.data[index].nameitem.querySelector('.unit').textContent = carts.data[index].unititem.querySelector('.price').textContent = carts.data[index].priceitem.querySelector('.num').value = carts.data[index].numitem.querySelector('.money').textContent = carts.data[index].money})// (四) 获取购物车中的单价,数量,金额分别组成数组,为更新购物车做准备const prices = document.querySelectorAll('.price')const nums = document.querySelectorAll('.num')const moneys = document.querySelectorAll('.money')const checks = document.querySelectorAll('.check')console.log(checks);/*** 分析:* 购物车中需要更新的数据:商品金额money,总数量total,总金额totalMoney* 要更新上面的数据,主要是依赖于更新单个商品的 数量num*///(五) 给商品数量的按钮添加change事件nums.forEach(function(num,index,arr){num.onchange = function(){// 判断该商品是否被选中,如果选中才计算(js秉承错误优先原则)if(!checks[index].checked) return false//1. 将每个数量取出来组成数组,再数组求和const numArr = [...arr].map(item=>parseInt(item.value))total.textContent = numArr.reduce((pre,cur)=>pre + cur)//2. 计算总金额=获取数组,再数组求和const moneyArr = [...arr].map((price,index)=>prices[index].textContent * nums[index].value)totalMoney.textContent = moneyArr.reduce((pre,cur)=>pre + cur)//3.单个商品价格=数量*单个价格moneys[index].textContent = num.value * prices[index].textContent}})//(六) 全选/全不选// 获取全选按钮const checkAll = document.querySelector('.check-all')let totalTmp = total.textContentlet totalMoneyTmp = totalMoney.textContent// console.log(checkAll);//为全选按钮添加事件checkAll.onchange = function(){// 遍历当前所有选中按钮的状态,并将全选按钮的值复制给它checks.forEach(item=>item.checked=checkAll.checked)if (checkAll.checked==false){let checkStatus = [...checks].every(function(check){return check.checked})if(checkStatus ==false) {total.textContent = 0totalMoney.textContent = 0}}else{total.textContent = totalTmptotalMoney.textContent = totalMoneyTmp}}// //遍历每个商品的复选框,并添加change事件checks.forEach(function(check,index){check.onchange = function(){//根据单个复选框状态来设置 全选按钮checkAll.checked = [...checks].every(item=>item.checked) //every只要有一个选中,就返回true,从而checkall.checked就是true////如果商品未选中,应该减去相对应的总数量和总金额if(check.checked == false) {total.textContent = total.textContent*1 - nums[index].value*1totalMoney.textContent = totalMoney.textContent*1 - moneys[index].textContent*1}else{total.textContent = total.textContent*1 + nums[index].value*1totalMoney.textContent = totalMoney.textContent*1 + moneys[index].textContent*1}}})
自己写了一遍,感觉还不是很通透.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号