Blogger Information
Blog 47
fans 0
comment 3
visits 45075
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
给购物车加上选择时自动计算功能
江流
Original
496 people have browsed it

给购物车加上选择时自动计算功能,分为两种情况:全选改变和单个商品选择改变。

  1. 全选复选框状态改变
    全选取消时,所有商品数量清零,全选时,所有商品数量设为1;
  2. 单个商品复选框状态改变
    取消选中时,对应商品数量设为0,选中时,数量设为1。
  1. // 全选复选框
  2. const checkAll = document.querySelector("#check-all");
  3. // 获取每行的复选框
  4. const checkItems = document.querySelectorAll(".item");
  5. // 获取全部数量框
  6. const numInput = document.querySelectorAll('input[type="number"]');
  7. checkAll.onchange = (ev) => {
  8. checkItems.forEach((item) => {
  9. item.checked = ev.target.checked;
  10. if (ev.target.checked) {
  11. numInput.forEach((num) => (num.value = 1));
  12. } else {
  13. numInput.forEach((num) => (num.value = 0));
  14. }
  15. // 调用自动运算函数
  16. autoCallculate();
  17. });
  18. };
  19. // 每一行的复选框状态发生变化时,检查是否全部选中,修改对应数量框的数值
  20. checkItems.forEach(function (item, index) {
  21. item.onchange = function (ev) {
  22. checkAll.checked = [...checkItems].every(function (item) {
  23. return item.checked;
  24. });
  25. if (ev.target.checked) {
  26. // 恢复选中,商品数量变为1
  27. numInput[index].value = 1;
  28. } else {
  29. // 取消选中时,商品数量变为0
  30. numInput[index].value = 0;
  31. }
  32. // 调用自动运算函数
  33. autoCallculate();
  34. };
  35. });
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:以后工作中, 还是要慢慢适应箭头函数, 毕竟现在很多案例全用它
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
1 comments
江流 2021-10-07 00:08:48
谢谢老师,我尽量多使用箭头函数。
1 floor
Author's latest blog post