「全選/反選/批量刪除」是後台管理系統高頻需求。本文提供原生 JavaScript 實現方案,涵蓋狀態同步、事件委派、批量收集 ID 並與 PHP 後端整合的完整鏈路。
<table id="data-table">
<thead>
<tr>
<th><input type="checkbox" id="select-all"> 全選</th>
<th>ID</th><th>名稱</th>
</tr>
</thead>
<tbody>
<tr><td><input type="checkbox" name="ids[]" value="1" class="row-check"></td><td>1</td><td>項目一</td></tr>
<tr><td><input type="checkbox" name="ids[]" value="2" class="row-check"></td><td>2</td><td>項目二</td></tr>
<tr><td><input type="checkbox" name="ids[]" value="3" class="row-check"></td><td>3</td><td>項目三</td></tr>
</tbody>
</table>
<button id="btn-delete">批量刪除</button>
<script>
document.addEventListener('DOMContentLoaded', () => {
const selectAll = document.getElementById('select-all');
const rowChecks = document.querySelectorAll('.row-check');
const btnDelete = document.getElementById('btn-delete');
// 全選/取消全選
selectAll.addEventListener('change', (e) => {
rowChecks.forEach(cb => cb.checked = e.target.checked);
});
// 行選中狀態同步更新全選框
rowChecks.forEach(cb => {
cb.addEventListener('change', () => {
const checkedCount = document.querySelectorAll('.row-check:checked').length;
selectAll.checked = checkedCount === rowChecks.length;
selectAll.indeterminate = checkedCount > 0 && checkedCount < rowChecks.length;
});
});
// 批量刪除收集 ID
btnDelete.addEventListener('click', () => {
const checkedIds = Array.from(document.querySelectorAll('.row-check:checked'))
.map(cb => cb.value);
if (checkedIds.length === 0) {
alert('請至少選擇一項');
return;
}
if (!confirm(`確定刪除 ${checkedIds.length} 項記錄?`)) return;
// 發送到後端
fetch('/api/delete-batch', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ids: checkedIds})
}).then(res => res.json())
.then(data => {
if (data.success) {
// 移除 DOM 行
checkedIds.forEach(id => {
document.querySelector(`.row-check[value="${id}"]`).closest('tr').remove();
});
// 重置全選狀態
selectAll.checked = false;
selectAll.indeterminate = false;
} else {
alert('刪除失敗: ' + data.message);
}
});
});
});
</script>
<form id="batch-form" method="POST" action="/admin/batch-delete">
<table>
<thead>
<tr>
<th><input type="checkbox" id="select-all" onclick="toggleAll(this)"></th>
<th>名稱</th>
</tr>
</thead>
<tbody>
<tr><td><input type="checkbox" name="ids[]" value="1"></td><td>項目一</td></tr>
<tr><td><input type="checkbox" name="ids[]" value="2"></td><td>項目二</td></tr>
</tbody>
</table>
<button type="submit" name="action" value="delete" onclick="return confirm('確定刪除?')>批量刪除</button>
</form>
<script>
function toggleAll(source) {
const checkboxes = document.querySelectorAll('input[name="ids[]"]');
checkboxes.forEach(cb => cb.checked = source.checked);
}
</script>
<?php
// POST 請求:ids 為陣列
$ids = $_POST['ids'] ?? [];
// JSON 請求
if (empty($ids) && $_SERVER['CONTENT_TYPE'] === 'application/json') {
$input = json_decode(file_get_contents('php://input'), true);
$ids = $input['ids'] ?? [];
}
// 驗證
if (empty($ids)) {
jsonResponse(['success' => false, 'message' => '未選擇任何項目']);
}
try {
$pdo = new PDO("mysql:host=localhost;dbname=app", "user", "pass");
$pdo->beginTransaction();
// 安全:預處理 + 佔位符動態生成
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "DELETE FROM items WHERE id IN ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
$pdo->commit();
jsonResponse(['success' => true, 'deleted' => $stmt->rowCount()]);
} catch (Exception $e) {
$pdo->rollBack();
jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
function jsonResponse(array $data, int $status = 200): never {
http_response_code($status);
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
?>
<?php
// 前端 JS 收集 ID 字串
function checkSubmit(name, url) {
const checkboxes = document.getElementsByName(name);
let str = '';
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
str += (str ? ',' : '') + checkboxes[i].value;
}
}
if (!str) { alert('未選擇內容'); return false; }
location.href = `${url}?ids=${str}&action=delall`;
}
// PHP 接收
$ids = explode(',', $_GET['ids'] ?? '');
// 同樣用預處理刪除
?>
<input type="hidden" id="selected-ids" name="selected_ids" value="">
<script>
const selectedIds = new Set();
const hiddenInput = document.getElementById('selected-ids');
function updateHiddenInput() {
hiddenInput.value = Array.from(selectedIds).join(',');
}
// 頁面載入時恢復
document.querySelectorAll('.row-check').forEach(cb => {
if (selectedIds.has(cb.value)) cb.checked = true;
});
// 選中變化時更新 Set
document.querySelectorAll('.row-check').forEach(cb => {
cb.addEventListener('change', () => {
if (cb.checked) selectedIds.add(cb.value);
else selectedIds.delete(cb.value);
updateHiddenInput();
});
});
// 全選按鈕邏輯調整:僅影響當前頁
document.getElementById('select-all').addEventListener('change', (e) => {
document.querySelectorAll('.row-check').forEach(cb => {
cb.checked = e.target.checked;
if (e.target.checked) selectedIds.add(cb.value);
else selectedIds.delete(cb.value);
});
updateHiddenInput();
});
</script>
<script>
// 單一事件監聽器處理所有 checkbox
document.getElementById('data-table').addEventListener('change', (e) => {
if (!e.target.matches('input[type="checkbox"]')) return;
if (e.target.id === 'select-all') {
// 全選邏輯
document.querySelectorAll('.row-check').forEach(cb => cb.checked = e.target.checked);
} else if (e.target.classList.contains('row-check')) {
// 行選中同步全選框
const all = document.querySelectorAll('.row-check');
const checked = document.querySelectorAll('.row-check:checked');
document.getElementById('select-all').checked = all.length === checked.length;
document.getElementById('select-all').indeterminate = checked.length > 0 && checked.length < all.length;
}
});
</script>
| 風險 | 防護措施 |
|---|---|
| CSRF 攻擊 | 表單加入 CSRF Token,AJAX 標頭攜帶 |
| ID 遍舉/越權刪除 | 後端驗證用戶權限、所有權 |
| 大量刪除導致超時 | 分批處理、異步隊列、限制單次最大數量 |
| SQL 注入 | 預處理語句、參數綁定(絕不拼接 SQL) |
| 誤刪無法恢復 | 軟刪除、回收站、操作日誌、確認對話框 |
indeterminate 屬性實現三狀態視覺反饋Array.from(...).map() 或 FormData 自動處理陣列Set 維護跨頁選中狀態,隱藏域提交