m0_59302338 2023-06-09 19:48 采纳率: 50%
浏览 29
已结题

购物车界面全选功能有问题,求修改

我点击全选,再点击单选框取消选中,金额会直接变成0,
就比如我有四个单选框,我点击全选后,取消一个本来是三个单选框的金额,
但是会直接为0,我觉得问题大概是出在单选框的监听方法上但是不知道怎么改了

    <script>
          // 从localStorage中获取购物车数据
          let cart = JSON.parse(localStorage.getItem('newArr')) || [];
          
          // 获取DOM元素
          const checkAll = document.getElementById('checkAllBtn');
          const cartBody = document.getElementById('cart-body');
          const totalPrice = document.getElementById('total-price');
          const buyBtn = document.getElementById('buy-btn');
          var strDate = "";
        
          
          // 渲染购物车表格
          function renderCart() {
            let html = '';
            let total = 0;
            cart.forEach((item, index) => {
              const { title, price, amount, img } = item;
              html += `
                <tr class="tr_goods">
                  <td class="td_check"><input type="checkbox" class="check-item" data-index="${index}"></td>
                    <td><img class='pay_pic' src='${img}'/></td>
                  <td>${title}</td>
                  <td>¥${price}</td>
                  <td><input type="number" class="amount-input" value="${amount}" min="1"></td>
                  <td class="td_Deletebtn"><button class="delete-btn" data-index="${index}">删除</button></td>
                </tr>
              `;
              
            });
            //console.log('渲染表格:' + total);
            
            cartBody.innerHTML = html;
            totalPrice.textContent = total;
          }
          
          // 更新localStorage中的购物车数据
          function updateCart() {
            localStorage.setItem('newArr', JSON.stringify(cart));
          }
          
          // 获取当前时间
          function gettime(){
                    var time=new Date();
                    var hour=time.getHours();
                    var min=time.getMinutes();
                    var sec=time.getSeconds();
                    strDate=time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate()+" "+hour+(min<10?":0":":")+min+(sec<10?":0":":")+sec;
                  }
          
          
          checkAll.addEventListener('click', () => {
            const checkItems = document.querySelectorAll('.check-item');
            checkItems.forEach(item => {
              item.checked = checkAll.checked;
            });
            let total = 0;
            if(checkAll.checked){
                cart.forEach(item => {
                total += item.price * item.amount;
            });
            totalPrice.textContent = total;
            }else{
                let total = 0;
                cart.forEach(item => {
                  item.checked == false;
                });
                totalPrice.textContent = total;
            }
          });
          
          cartBody.addEventListener('change', e => {
            if (e.target.classList.contains('check-item')) {
              const index = e.target.dataset.index;
              cart[index].checked = e.target.checked;
              checkAll.checked = document.querySelectorAll('.check-item:checked').length === cart.length;
              let total = 0;
              cart.forEach(item => {
                if (item.checked) {
                  total += item.price * item.amount;
                }
              });
              totalPrice.textContent = total;
            }
          });
          
          // 修改商品数量
          cartBody.addEventListener('input', e => {
            if (e.target.classList.contains('amount-input')) {
              const index = e.target.parentNode.parentNode.querySelector('.check-item').dataset.index;
              cart[index].amount = parseInt(e.target.value);
              cart[index].checked = true;
              updateCart();
              renderCart();
            }
          });
          
          // 删除商品
          cartBody.addEventListener('click', e => {
            if (e.target.classList.contains('delete-btn')) {
              const index = e.target.dataset.index;
              cart.splice(index, 1);
              localStorage.setItem('newArr', JSON.stringify(cart));
              updateCart();
              renderCart();
            }
          });
          
          // 购买商品
          buyBtn.addEventListener('click', () => {
              gettime();
              const checkedItems = cart.filter(item => item.checked);
              const totalPrice = checkedItems.reduce((total, item) => total + item.price * item.amount, 0);
              const purchaseList = checkedItems.map(item => ({ title: item.title, price: item.price, amount: item.amount }));
              if (purchaseList.length === 0) {
                alert('购物车为空,无法生成订单!');
                return;
              }
              alert(`您需要支付${totalPrice}元`);
              const order = {
                  id: Date.now().toString(),
                  time: strDate,
                  orderItems: purchaseList.map(item => ({
                      name: item.title,
                      quantity: item.amount,
                      price: item.price,
                      subtotal: item.price * item.amount
                  }))
              };
              localStorage.setItem('order_' + order.id, JSON.stringify(order));
              cart = cart.filter(item => !item.checked);
              updateCart();
              renderCart();
          });
          
          // 初始化购物车表格
          if (cartBody.children.length === 0) {
            // 第一次渲染
            renderCart();
            let total = 0
            totalPrice.textContent = 0;
            //console.log('第一次渲染完毕!');
          }
          
        </script>
    </body>
</html>

  • 写回答

1条回答 默认 最新

  • 自在猫先生 2023-06-12 11:08
    关注

    源于ChatGPT仅供参考:

    您的问题出在取消单个商品选择时,总价没有正确更新。具体地,在 `cartBody` 上的 `change` 事件监听函数中,当取消选择某个商品时,应将该商品的价格从当前总价中减去。可以在修改选中状态的代码后面添加如下代码段完成此操作:
    
    ```javascript
    if (!e.target.checked) {
      const index = e.target.dataset.index;
      total -= cart[index].price * cart[index].amount;
    }
    

    此外,在全选按钮的点击事件处理函数中,应将选择状态被取消的商品的状态设置为未选中,而不是仅仅将总价设为零。完整代码如下:

    checkAll.addEventListener('click', () => {
      const checkItems = document.querySelectorAll('.check-item');
      checkItems.forEach(item => {
        item.checked = checkAll.checked;
      });
      let total = 0;
      if (checkAll.checked) {
        cart.forEach(item => {
          total += item.price * item.amount;
        });
      } else {
        cart.forEach(item => {
          item.checked = false; // 取消所有商品的选择状态
        });
      }
      totalPrice.textContent = total;
    });
    

    希望这能帮助您解决问题!

    ```

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 7月27日
  • 修改了问题 6月9日
  • 创建了问题 6月9日

悬赏问题

  • ¥15 非科班怎么跑代码?如何导数据和调参
  • ¥15 福州市的全人群死因监测点死亡原因报表
  • ¥15 Altair EDEM中生成一个颗粒,并且各个方向没有初始速度
  • ¥15 系统2008r2 装机配置推荐一下
  • ¥500 服务器搭建cisco AnyConnect vpn
  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊
  • ¥15 快速扫描算法求解Eikonal方程咨询
  • ¥15 校内二手商品转让网站
  • ¥20 高德地图聚合图层MarkerCluster聚合多个点,但是ClusterData只有其中部分数据,原因应该是有经纬度重合的地方点,现在我想让ClusterData显示所有点的信息,如何实现?