(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>
// 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('刪除失敗');
}
}
prop() 替代 attr():jQuery 1.6+ 推薦操作 checked 等屬性用 prop,避免 1.9+ 版本失效。check-value,符合 HTML5 標準。$(document).on('change', '.rowCheck', ...) 確保生效。{status:1, msg:''},前端統一解析。若列表分頁,需在前端維护 selectedIds = new Set(),翻頁時根據此 Set 恢復勾選,提交時發送完整 ID 列表。此處不再展開,可參考 jquery.datatables 或 bootstrap-table 的實現。