原生js实现购物车全选/全不选逻辑

博客背景: 由于最近要开发一款电商小程序项目,购物车模块正好要用到这些知识,前来复习一下该功能逻辑。

  <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        background-color: #ccc;
      }

      .jdTabContent {
        width: 600px;
        height: 800px;
        margin: 200px auto;
      }

      .section {
        position: relative;
        padding: 15px;
        border-radius: 10px;
        background: #fff;
        color: #262626;
        margin-top: 10px;
      }

      .head_wrap {
        padding: 15px 10px;
      }
      .cart-footer {
        width: 100%;
        height: 60px;
        background-color: #fff;
        display: flex;
        align-items: center;
        margin-top: 10px;
        border-radius: 10px;
        padding-left: 25px;
      }
    </style>

  <body>
    <div class="jdTabContent">
      <div class="section">
        <div class="head_wrap">
          <input
            class="merchant_checkbox"
            type="checkbox"
          />
          <span>法德鹿皮旗舰店</span>
        </div>
      </div>
      <div class="section">
        <div class="head_wrap">
          <input
            class="merchant_checkbox"
            type="checkbox"
          />
          <span>樊者旗舰店</span>
        </div>
      </div>
      <div class="cart-footer">
        <input type="checkbox" id="all_select" />
        <span>全选</span>
      </div>
    </div>
    <script>
     const all_select = document.querySelector('#all_select')
     const head_checkbox = document.querySelectorAll('.merchant_checkbox')
     

      // 全选/全不选 父控制子
      all_select.addEventListener('click', function () {
        for (let i = 0, len = head_checkbox.length; i < len; i++) {
          head_checkbox[i].checked = this.checked
        }
      })

      // 方法判断一: 子控制父
      for (let i = 0, len = head_checkbox.length; i < len; i++) {
        head_checkbox[i].onclick = function () {
          // 1: 假设子checkbox已全部选中了
          let flag = true
          // 2: 修改flag
          for (let j = 0, j_len = head_checkbox.length; j < j_len; j++) {
            // 只要有一个为不选中flag就不能为true
            if (!head_checkbox[j].checked) {
               flag = false
              }         
            }
           all_select.checked = flag
        }
      }

      // 方法判断二: 子控制父
      let count = 0
      for (let i = 0, len = head_checkbox.length; i < len; i++) {
        head_checkbox[i].onclick = function () {
          this.checked ? count++ : count--
          all_select.checked = count === head_checkbox.length
        }
      }
    </script>
  </body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值