刪除操作不可逆,提供確認對話框是基本 UX 要求。本文展示三種從簡單到進階的實作方案,幫助開發者根據專案需求選擇最適合的方式。
<!-- HTML 結構 -->
<a href="javascript:void(0)"
class="del"
data-url="{:U('Athlete/del/',array('uid'=>$vo['id']))}"
data-name="{$vo.name}">
刪除
</a>
<script>
$(function() {
// 事件委派:支援動態新增元素
$(document).on('click', '.del', function(e) {
e.preventDefault();
var $link = $(this);
var delUrl = $link.data('url');
var itemName = $link.data('name');
// 使用原生 confirm(或替換為美化插件如 SweetAlert2)
if (confirm('你真的打算刪除【' + itemName + '】嗎?')) {
top.window.location.href = delUrl;
}
});
});
</script>
優點:支援動態元素、資料屬性分離、易維護、可替換對話框插件
<a href="del.asp?areyou=delete&id=1"
onclick="return confirm('確認要刪除該內容?')">
刪除
</a>
原理:confirm 回傳 false 時取消連結預設行為
缺點:HTML 與行為耦合、難維護、無法複用邏輯
<script>
function delSure(message) {
return confirm(message || '確定要刪除?');
}
</script>
<a href="del.asp?id=<%=rs('id')%>" onclick="return delSure()">刪除</a>
<a href="del.asp?id=<%=rs('id')%>" onclick="return delSure('確定刪除此用戶?')">刪除</a>
優點:邏輯集中、支援自訂訊息、相容舊專案
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
$(document).on('click', '.del', async function(e) {
e.preventDefault();
var $link = $(this);
const result = await Swal.fire({
title: '確定刪除?',
text: "將刪除【" + $link.data('name') + "】,此操作無法復原!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6',
confirmButtonText: '確定刪除',
cancelButtonText: '取消',
reverseButtons: true
});
if (result.isConfirmed) {
top.window.location.href = $link.data('url');
}
});
<a href="..." class="del" role="button" aria-label="刪除 {{name}}">刪除</a>
| 場景 | 推薦方案 | 關鍵考量 |
|---|---|---|
| 現代專案、需維護性 | 方案一 + SweetAlert2 | 事件委派、資料屬性、可替換 UI |
| 舊專案、快速修改 | 方案三 | 最小改動、向後相容 |
| 靜態頁面、單一刪除 | 方案二 | 零 JS 依賴、最簡潔 |
| 高安全性需求 | 方案一 + 後端雙重驗證 | CSRF、權限、審計日誌 |
選對方案,讓刪除確認既安全又優雅。