基於 jQuery UI Dialog 封裝統一彈窗組件,支持 Alert(提示)、Confirm(確認)、Error(錯誤)、Warning(警告)四種類型,圖標區分、回調函數、模態顯示、自動清理重複實例。本文提供完整封裝代碼、調用示例、擴展建議。
var Dialog = (function() {
var ICONS = {
alert: 'tipmsg_icoInfo',
confirm: 'tipmsg_icoConfirm',
error: 'tipmsg_icoError',
warning: 'tipmsg_icoWarning'
};
function buildHtml(type, msg) {
var icon = ICONS[type] || ICONS.alert;
return "<div id='" + type + "Div' style='display:none'>" +
"<p><span class='" + icon + "' style='float:left;margin:0 7px 50px 0;width:35px;height:35px'></span>" +
msg + "</p></div>";
}
function openDialog(type, title, msg, buttons) {
var selector = '#' + type + 'Div';
$(selector).remove(); // 清理舊實例
$('body').append(buildHtml(type, msg)); // 插入新 DOM
$(selector).dialog({
modal: true,
title: title,
buttons: buttons,
close: function() { $(this).dialog('destroy').remove(); } // 關閉銷毀
});
}
return {
alert: function(msg, okCb) {
openDialog('alert', '提示', msg, {
'確定': function() { if (okCb) okCb(); $(this).dialog('close'); }
});
},
confirm: function(msg, okCb, cancelCb) {
openDialog('confirm', '確認', msg, {
'確定': function() { if (okCb) okCb(); $(this).dialog('close'); },
'取消': function() { if (cancelCb) cancelCb(); $(this).dialog('close'); }
});
},
error: function(msg, okCb) {
openDialog('error', '錯誤', msg, {
'確定': function() { if (okCb) okCb(); $(this).dialog('close'); }
});
},
warning: function(msg, okCb) {
openDialog('warning', '警告', msg, {
'確定': function() { if (okCb) okCb(); $(this).dialog('close'); }
});
}
};
})();
.tipmsg_icoInfo { background: url(info.png) no-repeat center; }
.tipmsg_icoConfirm { background: url(question.png) no-repeat center; }
.tipmsg_icoError { background: url(error.png) no-repeat center; }
.tipmsg_icoWarning { background: url(warning.png) no-repeat center; }
/* 或用 FontAwesome */
.tipmsg_icoInfo::before { content: '\f05a'; font-family: FontAwesome; }
.tipmsg_icoConfirm::before { content: '\f128'; font-family: FontAwesome; }
.tipmsg_icoError::before { content: '\f06a'; font-family: FontAwesome; }
.tipmsg_icoWarning::before { content: '\f071'; font-family: FontAwesome; }
// 簡單提示
Dialog.alert('操作成功!');
// 帶回調確認
Dialog.confirm('確定刪除?',
function() { ajaxDelete(id); },
function() { console.log('用戶取消'); }
);
// 錯誤提示
Dialog.error('網絡請求失敗,請重試。', function() { location.reload(); });
// 警告
Dialog.warning('數據未保存,離開將丟失。');
封裝統一 Dialog API 能大幅減少項目中重複的彈窗代碼,提升一致性與可維護性。核心要點:單例模式管理 DOM、圖標語義化、回調解耦、關閉時銷毀防洩漏。新項目推薦直接接入成熟組件庫或原生 `