本文示範如何借助 jQuery UI 打造自訂的 confirm 確認框。透過 HTML 自訂對話框的內容與外觀,並自行定義按鈕;本例規劃了一個「Confirm」確認鈕與一個「Cancel」取消鈕。
<button id="callConfirm">Confirm!</button> <div id="dialog" title="Confirmation Required">Are you sure about this?</div>
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
關鍵在於把 autoOpen 設為 false,讓對話框在初始化時不自動彈出,改由點擊按鈕時呼叫 dialog("open") 開啟;每個按鈕各自綁定對應的點擊行為即可。希望本文對大家的 jQuery 開發有所幫助。