萬盛學電腦網

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

jQuery UI Dialog 打造自定義 Confirm 確認框:替代原生 confirm 的最佳實踐

為什麼要替換原生 confirm()?

  • 樣式不可控(瀏覽器原生 UI,無法適配品牌設計)
  • 阻塞主線程,體驗差
  • 無法自定義按鈕文字、圖標、佈局
  • 移動端體驗極差

jQuery UI Dialog 方案

依賴:jQuery + jQuery UI (含 CSS)。現代專案建議改用 SweetAlert2、Vex 或原生 <dialog> 元素。

基礎實現

<!-- HTML -->
<button id="openConfirm">刪除記錄</button>

<div id="confirmDialog" title="確認操作" style="display:none;">
  <p><span class="ui-icon ui-icon-alert" style="float:left;margin:12px 12px 20px 0;"></span>確定要刪除這條記錄嗎?此操作不可恢復。</p>
</div>

<script>
$(function () {
  var $dialog = $('#confirmDialog').dialog({
    autoOpen: false,
    modal: true,
    resizable: false,
    draggable: false,
    width: 400,
    buttons: {
      '確定刪除': {
        text: '確定刪除',
        class: 'ui-button-danger',
        click: function () {
          $(this).dialog('close');
          executeDelete(); // 業務邏輯
        }
      },
      '取消': {
        text: '取消',
        click: function () { $(this).dialog('close'); }
      }
    },
    close: function () { /* 關閉後清理 */ }
  });

  $('#openConfirm').click(function () {
    $dialog.dialog('open');
  });

  function executeDelete() {
    // AJAX 刪除...
    console.log('執行刪除邏輯');
  }
});
</script>

封裝為可復用函式

function confirmDialog(options) {
  var opts = $.extend({
    title: '確認',
    message: '確定執行此操作?',
    confirmText: '確定',
    cancelText: '取消',
    confirmClass: 'ui-button-danger',
    onConfirm: $.noop,
    onCancel: $.noop
  }, options);

  // 動態創建對話框
  var $dialog = $('
').html('

' + opts.message + '

') .appendTo('body') .dialog({ autoOpen: true, modal: true, resizable: false, draggable: false, width: 400, title: opts.title, buttons: [ { text: opts.confirmText, class: opts.confirmClass, click: function () { $(this).dialog('close').remove(); opts.onConfirm(); } }, { text: opts.cancelText, click: function () { $(this).dialog('close').remove(); opts.onCancel(); } } ], close: function () { $(this).dialog('destroy').remove(); } }); } // 使用 $('#deleteBtn').click(function () { confirmDialog({ title: '刪除確認', message: '確定刪除「重要文檔」?
此操作將永久移除所有關聯數據。', confirmText: '永久刪除', onConfirm: function () { deleteDocument(); } }); });

現代原生替代:<dialog> 元素(無依賴)

<dialog id="nativeConfirm">
  <form method="dialog">
    <p>確定要刪除嗎?</p>
    <menu>
      <button value="cancel">取消</button>
      <button value="confirm" id="nativeConfirmBtn">確定</button>
    </menu>
  </form>
</dialog>

<style>
  dialog { border:none; border-radius:8px; padding:24px; max-width:400px; box-shadow:0 4px 24px rgba(0,0,0,.15); }
  dialog::backdrop { background:rgba(0,0,0,.4); }
  menu { display:flex; justify-content:flex-end; gap:8px; margin-top:16px; }
  button { padding:8px 16px; border-radius:4px; border:1px solid #ddd; background:#fff; cursor:pointer; }
  button[value="confirm"] { background:#dc3545; color:#fff; border-color:#dc3545; }
</style>

<script>
var dialog = document.getElementById('nativeConfirm');
var confirmBtn = document.getElementById('nativeConfirmBtn');

confirmBtn.onclick = function () {
  dialog.close('confirm');
  executeDelete();
};

dialog.addEventListener('close', function () {
  if (dialog.returnValue !== 'confirm') {
    console.log('用戶取消');
  }
});

function openConfirm() {
  dialog.showModal(); // 模態
}
// 非模態用 dialog.show()
</script>

對比總結

方案體積相容性自定義度推薦場景
原生 confirm()0100%極低快速原型、內部工具
jQuery UI Dialog~200KB (含jQuery)IE8+高舊專案維護、已依賴 jQuery UI
SweetAlert2~40KB現代瀏覽器極高新專案、需豐富動畫/圖標
原生 <dialog>0Chrome 37+, Firefox 53+, Safari 15.4+高(CSS 完全控制)現代專案、追求零依賴

結語

自定義 Confirm 是提升產品專業度的細節關鍵。新專案首選原生 <dialog> + CSS 動畫,零依賴、語義化、無障礙友善;舊專案若已引入 jQuery UI,本文封裝方案可直接落地。核心原則:**業務邏輯與 UI 解耦**,確認框只負責「詢問與回調」,具體刪除/提交邏輯由調用方注入。

copyright © 萬盛學電腦網 all rights reserved