Blogger Information
Blog 21
fans 0
comment 0
visits 14828
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
(1111)购物车案例
Yuming
Original
665 people have browsed it

购物车案例

  1. 用 jQuery 改写购物车的全选/全不选功能
  1. $("#check-all").click((ev) =>
  2. $("[name='itemId']").each((index, btn) => (btn.checked = ev.target.checked))
  3. );
  4. // 每个复选框的change事件回调
  5. $("[name='itemId']").each(function (index, btn) {
  6. $(btn).change(function () {
  7. let count = 0;
  8. $("[name='itemId']").each((index, btn) => btn.checked && count++);
  9. // 如果数量等于全部按钮的数量,就全选按钮勾选,反之不选
  10. $("[name='itemId']").length == count
  11. ? ($("#check-all")[0].checked = true)
  12. : ($("#check-all")[0].checked = false);
  13. });
  14. });
  1. 用 jq 改写金额自动计算
  1. // 获取每个商品的数量
  2. const numArr = Array.from($('input[type="number"]'));
  3. // 每个商品的单价
  4. const unitPriceArr = Array.from($("tbody>tr>td:nth-of-type(5)"));
  5. // 获取每个商品的金额(计算值,当前为空)
  6. const amountArr = Array.from($("tbody>tr>td:last-of-type"));
  7. numArr.forEach((item) => $(item).change(() => autoCalculate()));
  8. window.addEventListener("load", autoCalculate, false);
  9. function autoCalculate() {
  10. // 1. 计算商品总数
  11. $("#total-num")[0].innerHTML = numArr.reduce(
  12. (pre, next) => (pre += parseInt(next.value)),
  13. 0
  14. );
  15. // 2. 计算没见商品的金额
  16. amountArr.forEach(
  17. (item, index) =>
  18. (item.innerHTML = unitPriceArr[index].innerHTML * numArr[index].value)
  19. );
  20. //3. 计算总金额
  21. $("#total-amount")[0].innerHTML = amountArr.reduce(
  22. (pre, next) => (pre += parseInt(next.innerHTML)),
  23. 0
  24. );
  25. }
  1. 为购物车的自动计算功能添加新功能,全选,单选时也能自动计算
  1. btn.checked
  2. ? ($("#total-num")[0].innerHTML =
  3. parseInt($("#total-num")[0].innerHTML) +
  4. parseInt($('input[type="number"]')[index].value))
  5. : ($("#total-num")[0].innerHTML =
  6. $("#total-num")[0].innerHTML -
  7. $('input[type="number"]')[index].value);
  8. });

全选自动计算

  1. // 添加全选按钮事件
  2. $("#check-all").click(function (ev) {
  3. $("[name='itemId']").each((index, btn) => {
  4. btn.checked = ev.target.checked;
  5. btn.checked ? autoCalculate() : ($("#total-num")[0].innerHTML = 0);
  6. });
  7. });

  • 总结:购物车案例需要的是清晰的逻辑,对 DOM 元素熟悉操作,全选,单选按钮是单个对象和数组对象的 dom 操作,类数组转换为数组,数值运算,属性获取等等,这些常规操作,在购物车案例里面能够得到很好的锻炼。
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
0 comments
Author's latest blog post