仿写购物车项目

编辑: admin 分类: 电脑知识 发布时间: 2023-06-14 来源:互联网
  1. import carts from "./carts.js"
  2. const items = document.querySelectorAll('.carts-body .item')
  3. const total = document.querySelector('.total')
  4. const totalMoney = document.querySelector('.total-money')
  5. items.forEach((item, index)=> {
  6. item.querySelector('.id').textContent = carts.data[index].id
  7. item.querySelector('.name').textContent = carts.data[index].name
  8. item.querySelector('.unit').textContent = carts.data[index].unit
  9. item.querySelector('.price').textContent = carts.data[index].price
  10. item.querySelector('.num').value = carts.data[index].num
  11. item.querySelector('.money').textContent = carts.data[index].money
  12. })
  13. total.textContent = carts.total
  14. totalMoney.textContent = carts.totalMoney
  15. const prices = document.querySelectorAll('.carts-body .price')
  16. const nums = document.querySelectorAll('.carts-body .num')
  17. const monies = document.querySelectorAll('.carts-body .money')
  18. const checks = document.querySelectorAll('.carts-body .check')
  19. // forEach(在遍历的数组,数组的索引,数组)
  20. nums.forEach((num, index, arr)=>{
  21. num.onchange = ()=>{
  22. if(!checks[index].checked) return false
  23. monies[index].textContent = prices[index].textContent * num.value
  24. const numArr = [...arr].map((item)=> parseInt(item.value))
  25. total.textContent = numArr.reduce((pre, cur)=>pre + cur)
  26. const moneyArr = [...monies].map((item)=> parseFloat(item.textContent))
  27. totalMoney.textContent = moneyArr.reduce((pre, cur)=>pre + cur)
  28. }
  29. })
  30. const checkAll = document.querySelector('.check-all')
  31. let totalTmp = total.textContent
  32. let totalMoneyTmp = totalMoney.textContent
  33. checkAll.onchange = ()=>{
  34. checks.forEach((check)=>check.checked = checkAll.checked)
  35. if(checkAll.checked == false){
  36. let itemStatus = [...checks].every(item=>item.checked == false)
  37. if(itemStatus == true){
  38. total.textContent = 0
  39. totalMoney.textContent = 0
  40. }
  41. }else{
  42. total.textContent = totalTmp
  43. totalMoney.textContent = totalMoneyTmp
  44. }
  45. }
  46. checks.forEach((check, index)=>{
  47. check.onchange = () =>{
  48. checkAll.checked = [...checks].every(item=>item.checked)
  49. if(check.checked == false){
  50. total.textContent -= nums[index].value
  51. totalMoney.textContent -= monies[index].textContent
  52. }else{
  53. total.textContent = total.textContent * 1 + nums[index].value * 1
  54. totalMoney.textContent = totalMoney.textContent * 1 + monies[index].textContent * 1
  55. }
  56. }
  57. })
总结:

把购物车项目js部分边看边写了一遍,把所有函数都变为箭头函数,简化代码,条理也很清楚;投票项目中把count赋值改为count = data[index]就可以把原始赋值带入;计划后续有时间自己再完全重写一遍购物车项目,包括CSS、html和js部分全部重写。

【文章原创作者:cc防御 http://www.558idc.com/gfip.html提供,感恩】