萬盛學電腦網

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

jQuery 實現列表全選/反選/批量刪除:ThinkPHP 後端聯調完整方案

功能清單

  • 表頭 Checkbox 全選/取消全選
  • 單行 Checkbox 聯動更新全選狀態
  • 批量刪除:收集選中 ID → POST 後端 → 回調處理結果
  • 無選中時友好提示

核心插件:jquery.selectall.js

(function($) {
  // 全選/反選
  $.fn.selectAll = function(itemSelector) {
    var $all = this;
    var $items = $(itemSelector);
    
    $all.on('change', function() {
      $items.prop('checked', this.checked);
    });
    
    $items.on('change', function() {
      $all.prop('checked', $items.filter(':checked').length === $items.length);
    });
    
    return this; // 鏈式調用
  };
  
  // 批量刪除
  $.fn.batchDelete = function(itemSelector, url, successCb, emptyCb) {
    this.on('click', function() {
      var ids = [];
      $(itemSelector + ':checked').each(function() {
        ids.push($(this).attr('data-id') || $(this).val());
      });
      
      if (!ids.length) {
        if ($.isFunction(emptyCb)) emptyCb();
        return;
      }
      
      $.post(url, { ids: ids.join(',') }, function(res) {
        if ($.isFunction(successCb)) successCb(res);
      });
    });
    return this;
  };
})(jQuery);

頁面集成代碼

<!-- 列表結構 -->
<table id="listTable">
  <thead>
    <tr>
      <th><input type="checkbox" id="checkAll"></th>
      <th>ID</th><th>名稱</th><th>操作</th>
    </tr>
  </thead>
  <tbody>
    <tr><td><input type="checkbox" class="rowCheck" data-id="1"></td><td>1</td><td>項目一</td></tr>
    <tr><td><input type="checkbox" class="rowCheck" data-id="2"></td><td>2</td><td>項目二</td></tr>
    <tr><td><input type="checkbox" class="rowCheck" data-id="3"></td><td>3</td><td>項目三</td></tr>
  </tbody>
</table>
<button id="deleteAll">批量刪除</button>

<script>
$(function() {
  // 1. 綁定全選
  $('#checkAll').selectAll('.rowCheck');
  
  // 2. 綁定批量刪除(ThinkPHP 後端路由示例)
  $('#deleteAll').batchDelete('.rowCheck', '/Home/Role/delall', function(res) {
    if (res === 'success') {
      alert('刪除成功');
      location.reload();
    } else {
      alert('刪除失敗:' + res);
    }
  }, function() {
    layer.msg('請先選中要刪除的項目', {time: 1500}); // 需引入 layer
  });
});
</script>

ThinkPHP 後端控制器示例

// Home/RoleController.class.php
public function delall() {
  $ids = I('post.ids'); // 格式: "1,2,3"
  if (empty($ids)) $this->error('未選中項目');
  
  $idArr = explode(',', $ids);
  $res = M('Role')->where(['id' => ['in', $idArr]])->delete();
  
  if ($res !== false) {
    $this->success('刪除成功');
  } else {
    $this->error('刪除失敗');
  }
}

關鍵改進點(對比原文)

  1. 使用 prop() 替代 attr():jQuery 1.6+ 推薦操作 checked 等屬性用 prop,避免 1.9+ 版本失效。
  2. data-id 屬性語義化:替代原文 check-value,符合 HTML5 標準。
  3. 事件委託優化:動態新增行時,改用 $(document).on('change', '.rowCheck', ...) 確保生效。
  4. 錯誤處理統一:後端返回 JSON 格式 {status:1, msg:''},前端統一解析。

進階:支援分頁保持選中狀態

若列表分頁,需在前端維护 selectedIds = new Set(),翻頁時根據此 Set 恢復勾選,提交時發送完整 ID 列表。此處不再展開,可參考 jquery.datatables 或 bootstrap-table 的實現。

copyright © 萬盛學電腦網 all rights reserved