萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現類淘寶購物車全選/反選/刪除功能完整示例

效果預覽

購物車全選效果圖

HTML 結構

<table class="cart-table">
  <thead>
    <tr id="titleTr">
      <th><input type="checkbox" id="selectAll" /></th>
      <th>商品</th>
      <th>價格</th>
      <th>數量</th>
      <th>小計</th>
    </tr>
  </thead>
  <tbody>
    <tr><td><input type="checkbox" class="item-check" /></td><td>商品 A</td><td>¥99</td><td>1</td><td>¥99</td></tr>
    <tr><td><input type="checkbox" class="item-check" /></td><td>商品 B</td><td>¥159</td><td>2</td><td>¥318</td></tr>
    <tr><td><input type="checkbox" class="item-check" /></td><td>商品 C</td><td>¥59</td><td>1</td><td>¥59</td></tr>
  </tbody>
</table>
<div class="actions">
  <button class="delete-btn">刪除選中</button>
</div>

核心 jQuery 邏輯

$(function() {
  const $table = $('.cart-table');
  const $selectAll = $('#selectAll');
  const $items = $table.find('.item-check');
  const $deleteBtn = $('.delete-btn');

  // 1. 全選/取消全選
  $selectAll.on('change', function() {
    const checked = this.checked;
    $items.prop('checked', checked).trigger('change'); // 觸發單項 change 以便同步其他邏輯
  });

  // 2. 單項變化更新全選狀態
  $items.on('change', function() {
    const total = $items.length;
    const checked = $items.filter(':checked').length;
    $selectAll.prop('checked', total > 0 && checked === total);
    $selectAll.prop('indeterminate', checked > 0 && checked < total); // 三態:全選/半選/無選
  });

  // 3. 刪除選中行
  $deleteBtn.on('click', function() {
    $items.filter(':checked').each(function() {
      $(this).closest('tr').remove();
    });
    // 刪除後重新檢查全選狀態
    $items.first().trigger('change'); // 觸發一次更新
  });

  // 4. 可選:計算總價
  function calcTotal() {
    let sum = 0;
    $items.filter(':checked').each(function() {
      const $row = $(this).closest('tr');
      const price = parseFloat($row.find('td:eq(2)').text().replace('¥', ''));
      const qty = parseInt($row.find('td:eq(3)').text());
      sum += price * qty;
    });
    $('#totalPrice').text('¥' + sum.toFixed(2));
  }
  $items.on('change', calcTotal);
  $selectAll.on('change', calcTotal);
  calcTotal();
});

關鍵點解析

  • .prop('checked', true/false) 優於 .attr('checked', 'checked'),正確操作 DOM 屬性而非 HTML 屬性。
  • indeterminate 屬性僅能通過 JS 設置,實現「半選」視覺狀態(陰影勾選框)。
  • 刪除時用 closest('tr') 定位行,避免索引錯亂。
  • 事件委託優化:若行動態增減,改用 $table.on('change', '.item-check', handler)。

CSS 樣式片段

.cart-table { border-collapse: collapse; width: 100%; }
.cart-table th, .cart-table td { border: 1px solid #ddd; padding: 8px; text-align: center; }
.cart-table thead tr { background: #f9f9f9; }
.actions { margin-top: 15px; }
.delete-btn { padding: 6px 12px; background: #e74c3c; color: #fff; border: none; border-radius: 4px; cursor: pointer; }
.delete-btn:hover { background: #c0392b; }
copyright © 萬盛學電腦網 all rights reserved