import carts from "./carts.js"
const items = document.querySelectorAll('.carts-body .item')
const total = document.querySelector('.total')
const totalMoney = document.querySelector('.total-money')
items.forEach((item, index)=> {
item.querySelector('.id').textContent = carts.data[index].id
item.querySelector('.name').textContent = carts.data[index].name
item.querySelector('.unit').textContent = carts.data[index].unit
item.querySelector('.price').textContent = carts.data[index].price
item.querySelector('.num').value = carts.data[index].num
item.querySelector('.money').textContent = carts.data[index].money
})
total.textContent = carts.total
totalMoney.textContent = carts.totalMoney
const prices = document.querySelectorAll('.carts-body .price')
const nums = document.querySelectorAll('.carts-body .num')
const monies = document.querySelectorAll('.carts-body .money')
const checks = document.querySelectorAll('.carts-body .check')
// forEach(在遍历的数组,数组的索引,数组)
nums.forEach((num, index, arr)=>{
num.onchange = ()=>{
if(!checks[index].checked) return false
monies[index].textContent = prices[index].textContent * num.value
const numArr = [...arr].map((item)=> parseInt(item.value))
total.textContent = numArr.reduce((pre, cur)=>pre + cur)
const moneyArr = [...monies].map((item)=> parseFloat(item.textContent))
totalMoney.textContent = moneyArr.reduce((pre, cur)=>pre + cur)
}
})
const checkAll = document.querySelector('.check-all')
let totalTmp = total.textContent
let totalMoneyTmp = totalMoney.textContent
checkAll.onchange = ()=>{
checks.forEach((check)=>check.checked = checkAll.checked)
if(checkAll.checked == false){
let itemStatus = [...checks].every(item=>item.checked == false)
if(itemStatus == true){
total.textContent = 0
totalMoney.textContent = 0
}
}else{
total.textContent = totalTmp
totalMoney.textContent = totalMoneyTmp
}
}
checks.forEach((check, index)=>{
check.onchange = () =>{
checkAll.checked = [...checks].every(item=>item.checked)
if(check.checked == false){
total.textContent -= nums[index].value
totalMoney.textContent -= monies[index].textContent
}else{
total.textContent = total.textContent * 1 + nums[index].value * 1
totalMoney.textContent = totalMoney.textContent * 1 + monies[index].textContent * 1
}
}
})
总结:
把购物车项目js部分边看边写了一遍,把所有函数都变为箭头函数,简化代码,条理也很清楚;投票项目中把count赋值改为count = data[index]就可以把原始赋值带入;计划后续有时间自己再完全重写一遍购物车项目,包括CSS、html和js部分全部重写。