萬盛學電腦網

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

JavaScript confirm 對話框與 LigerUI/LG 彈窗確認完整用法指南

一、原生 confirm() 基礎用法

基本語法

var result = confirm("訊息文字");
// 使用者點「確定」→ 返回 true
// 使用者點「取消」→ 返回 false

標準使用模式

if (confirm("確定要刪除此筆資料嗎?")) {
  // 使用者點擊「確定」
  deleteData(id);
  alert("刪除完成!");
} else {
  // 使用者點擊「取消」
  console.log("使用者取消操作");
}

簡潔寫法 (短路求值)

confirm("確定執行?") && doSomething();
// 或
confirm("確定?") ? doYes() : doNo();

完整可執行範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>confirm 示範</title>
  <style>
    .btn { padding: 10px 20px; margin: 5px; cursor: pointer; }
    .btn-danger { background: #dc3545; color: white; border: none; border-radius: 4px; }
    .btn-primary { background: #007bff; color: white; border: none; border-radius: 4px; }
  </style>
</head>
<body>
  <h3>原生 confirm() 示範</h3>
  <button class="btn btn-danger" onclick="deleteConfirm()">刪除資料 (原生 confirm)</button>
  <button class="btn btn-primary" onclick="customConfirm()">自訂樣式確認</button>
  <div id="log" style="margin-top:20px; padding:10px; background:#f8f9fa; border-radius:4px;"></div>

  <script>
    function log(msg) {
      $("#log").prepend("<div>" + new Date().toLocaleTimeString() + " - " + msg + "</div>");
    }
    
    function deleteConfirm() {
      if (confirm("確定要刪除此筆資料嗎?\n此操作無法復原!")) {
        log("✅ 使用者確認刪除");
        // 執行刪除邏輯...
      } else {
        log("❌ 使用者取消刪除");
      }
    }
    
    function customConfirm() {
      // 簡易自訂模態框示範
      var confirmed = window.confirm("這是自訂標題\n\n確定要繼續嗎?");
      log(confirmed ? "✅ 自訂確認" : "❌ 自訂取消");
    }
  </script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>

二、LigerUI / LG 彈窗確認 (企業級專案常用)

jQuery.ligerDialog.confirm

// 基本用法
$.ligerDialog.confirm('確定要刪除選中的記錄嗎?', function(yes) {
  if (yes) {
    f_delete();  // 執行刪除
  }
});

// 完整參數
$.ligerDialog.confirm({
  title: '確認刪除',
  content: '確定要刪除選中的 3 筆 記錄嗎?
此操作不可復原!', buttons: [ { text: '確定刪除', cls: 'btn-danger', onclick: function(item, dialog) { f_delete(); dialog.close(); }}, { text: '取消', onclick: function(item, dialog) { dialog.close(); }} ] });

LG.showSuccess / LG.showError / LG.tip (輕量提示)

// 成功訊息 (綠色,居中,自動關閉)
LG.showSuccess("更新成功!資料已儲存。");

// 錯誤訊息 (紅色,居中,需手動關閉)
LG.showError("更新失敗:網路連線異常,請稍後再試。");

// 輕量提示 (右下角,自動消失)
LG.tip("資料已自動儲存");
LG.tip("操作完成", "success");  // 可指定類型: success, error, warning, info

// 手動關閉所有 LG 提示
LG.closeAll();

LG 完整配置選項

LG.showSuccess = function(message, title, width, height) {
  return $.ligerDialog.success(message, title, width, height);
};

LG.showError = function(message, title, width, height) {
  return $.ligerDialog.error(message, title, width, height);
};

LG.tip = function(message, type) {
  // type: success, error, warning, info
  // 實作為右下角浮動提示,3 秒自動消失
  var icon = { success: '✅', error: '❌', warning: '⚠️', info: 'ℹ️' }[type] || '';
  $.ligerDialog.tip({ content: icon + ' ' + message, type: type });
};

三、現代化替代方案 (不依賴 LigerUI)

原生 元素 (HTML5.2+)

<dialog id="confirmDialog">
  <h3>確認刪除</h3>
  <p>確定要刪除此項目嗎?此操作無法復原。</p>
  <menu>
    <button value="cancel" id="btnCancel">取消</button>
    <button value="confirm" id="btnConfirm" class="danger">刪除</button>
  </menu>
</dialog>

<script>
const dialog = document.getElementById('confirmDialog');
const btnConfirm = document.getElementById('btnConfirm');
const btnCancel = document.getElementById('btnCancel');

function showConfirm(message) {
  return new Promise((resolve) => {
    dialog.querySelector('p').textContent = message;
    dialog.showModal();
    
    const onClose = (value) => {
      dialog.close();
      cleanup();
      resolve(value);
    };
    
    const cleanup = () => {
      btnConfirm.removeEventListener('click', onConfirm);
      btnCancel.removeEventListener('click', onCancel);
      dialog.removeEventListener('close', onDialogClose);
    };
    
    const onConfirm = () => onClose(true);
    const onCancel = () => onClose(false);
    const onDialogClose = () => onClose(false); // ESC 或 backdrop click
    
    btnConfirm.addEventListener('click', onConfirm);
    btnCancel.addEventListener('click', onCancel);
    dialog.addEventListener('close', onDialogClose);
  });
}

// 使用
async function handleDelete() {
  const confirmed = await showConfirm("確定刪除?");
  if (confirmed) { await deleteItem(); }
}
</script>

SweetAlert2 (最流行現代替代)


// CDN: https://cdn.jsdelivr.net/npm/sweetalert2@11
// 基本確認
const result = await Swal.fire({
  title: '確定刪除?',
  text: '此操作無法復原!',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: '確定刪除',
  cancelButtonText: '取消',
  confirmButtonColor: '#dc3545',
  reverseButtons: true
});

if (result.isConfirmed) {
  await deleteData();
  await Swal.fire('已刪除!', '資料已永久移除。', 'success');
}

// 載入狀態
Swal.fire({
  title: '處理中...',
  allowOutsideClick: false,
  didOpen: () => Swal.showLoading()
});

Bootstrap 5 Modal

<div class="modal fade" id="confirmModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">確認操作</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">確定要執行此操作嗎?</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-danger" id="modalConfirmBtn">確定</button>
      </div>
    </div>
  </div>
</div>

<script>
var confirmModal = new bootstrap.Modal(document.getElementById('confirmModal'));
var confirmCallback = null;

function showConfirm(message, callback) {
  confirmCallback = callback;
  document.querySelector('#confirmModal .modal-body').textContent = message;
  confirmModal.show();
}

document.getElementById('modalConfirmBtn').addEventListener('click', function() {
  confirmModal.hide();
  if (confirmCallback) confirmCallback(true);
});
</script>

四、最佳實踐總結

場景推薦方案理由
簡單刪除確認原生 confirm()零依賴、阻塞式、語意明確
需自訂樣式/內容SweetAlert2 / 現代、無依賴/輕量、Promise API
LigerUI 既有專案$.ligerDialog.confirm / LG.show*風格一致、整合現有代碼
Bootstrap 專案Bootstrap Modal框架內建、無額外依賴
複雜表單彈窗原生 + FormData語意化、無障礙支援、標準化

遷移建議

若專案仍大量使用 LigerUI,建議建立統一封裝層:

window.Confirm = {
  // 統一介面,內部可隨時切換實作
  ask: function(message, options) {
    return new Promise(function(resolve) {
      // 目前用 LigerUI
      $.ligerDialog.confirm(message, function(yes) { resolve(yes); });
      
      // 未來遷移只需改這裡:
      // Swal.fire({...}).then(r => resolve(r.isConfirmed));
      // showNativeDialog(message).then(resolve);
    });
  },
  
  success: function(msg) { LG.showSuccess(msg); },
  error: function(msg) { LG.showError(msg); },
  tip: function(msg, type) { LG.tip(msg, type); }
};

// 業務代碼統一呼叫
async function deleteUser(id) {
  if (await Confirm.ask("確定刪除用戶 " + id + "?")) {
    await api.deleteUser(id);
    Confirm.success("刪除成功");
  }
}

總結

原生 confirm() 適合簡單場景,LigerUI 的 $.ligerDialog.confirm 和 LG.show* 適合既有企業級專案維護。新專案強烈建議採用 **SweetAlert2** 或 **原生

** 元素,獲得更好的使用者體驗、無障礙支援、現代化 API (Promise) 且無舊框架依賴包袱。

copyright © 萬盛學電腦網 all rights reserved