iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
Modern Web

Modern Web × AI《拖延怪日記》:語錄陪伴擺脫拖延系列 第 8

【Day 8】- 入門 JavaScript 網頁架設:刪除清單資料前的確認視窗(Confirm)

  • 分享至 

  • xImage
  •  

摘要
Day 7 我們已經能「按下刪除 → 立即移除一筆紀錄」。
今天加上 window.confirm:刪除前先詢問使用者,避免手滑誤刪。
同時保留 Day 7 的兩個好習慣:事件委派、多分頁同步(storage 事件)。

為什麼要加確認?

  • 避免誤刪:多一步思考空間。
  • 符合直覺:幾乎所有產品的刪除都會先問。
  • 漸進增量:先有確認,後續再加 Undo 復原。

核心流程(在 Day 7 基礎上多一步)

  1. 使用事件委派在 監聽刪除按鈕點擊(以 data-id 傳主鍵)。
  2. 觸發刪除前,window.confirm('確定要刪除嗎?')。
  3. 使用 filter 依 id 產生新陣列寫回(不可變性)。
  4. renderHistory() 重新渲染。
  5. 若找不到該筆(被其他分頁刪掉),用 alert 提示。
  6. 監聽 storage 事件,跨分頁自動同步 UI。

實作步驟

假設已有 STORAGE_KEY、readRecords()、writeRecords()(Day 5 進階)。
仍採事件委派,不暴露全域函式。
JavaScript:

// ---- 事件委派:監聽 <ul> click,判斷是否點到刪除按鈕 ----
document.getElementById('historyList').addEventListener('click', (e) => {
  const btn = e.target.closest('button.btn-delete');
  if (!btn) return; // 點到的是其他位置
  const id = btn.dataset.id;
  // 新增:刪除前確認
  const ok = window.confirm('確定要刪除嗎?');
  if (!ok) return;

  const removed = deleteRecordById(id);
  if (!removed) {
    alert('找不到這筆紀錄,可能已被移除或在其他分頁修改。');
  }
  renderHistory();
});

// ---- 多分頁同步:其他分頁變更 STORAGE_KEY 時自動重繪 ----
window.addEventListener('storage', (e) => {
  if (e.key === STORAGE_KEY) {
    renderHistory();
  }
});

// 清空全部修改 Day 7 的做法:
document.getElementById('clearBtn').addEventListener('click', () => {
  if (!window.confirm('確定要清空所有紀錄嗎?')) return;
  localStorage.removeItem(STORAGE_KEY);
  renderHistory();
});

驗證

  1. 新增 2~3 筆資料。

  2. 點「刪除」→ 跳出確認 → 按「取消」:不刪除;按「確定」:該筆移除並重繪。
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913XqF9yuidEI.png
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913DwENr1GFRd.png
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913oVmNn84sAc.png

  3. 開兩個分頁同時打開本頁:在 A 分頁刪除,切到 B 分頁應自動同步(storage 事件)。
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913TGcsIiqfDl.png
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913ptVRcVGVVX.png
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913wbaQ8z50Ul.png

  4. 測試「清空記錄」→ 按「確定」:該筆移除並重繪。
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913Nd4mjOZEOW.png
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913RFv6IMUiCp.png
    https://ithelp.ithome.com.tw/upload/images/20250823/20177913k05pdptHZP.png

  5. 錯誤處理:在 A 分頁刪除後,在 B 分頁對同一筆再按「刪除」時 → 出現「找不到紀錄」提示。


上一篇
【Day 7】- 入門 JavaScript 網頁架設:刪除單筆紀錄(Delete)
下一篇
【Day 9】- 入門 JavaScript 網頁架設:Undo
系列文
Modern Web × AI《拖延怪日記》:語錄陪伴擺脫拖延20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言