本文以一個「刪除確認」的實際情境為主線,帶你把 jQuery UI 的 Dialog 元件從零跑起來:從環境準備、DOM 結構、樣式表引入,一路做到點擊按鈕才彈出、模態遮罩、以及自訂按鈕與回呼。
頁面上先放一顆觸發用的按鈕:
<input type="button" value="刪除" id="btn" />
接著引入 jQuery 主程式,並在 ready 階段掛上點擊事件,確認事件本身能正常觸發:
<script type="text/javascript" src="scripts/jquery-1.4.2.js"></script>
$(function() {
$("#btn").click(function() {
alert("btn 被點擊啦!");
});
});
對話框的本體其實就是一個普通的 div,標題由 title 屬性提供,內容可以放任意 HTML:
<div id="dialog-confirm" title="Empty the recycle bin?">
<p>
<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
These items will be permanently deleted and cannot be recovered. Are you sure?
</p>
</div>
要讓 Dialog 運作,除了核心之外還需要 widget、mouse、button、draggable、position 等模組,依序引入即可:
<script type="text/javascript" src="scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="scripts/jquery.ui.mouse.js"></script>
<script type="text/javascript" src="scripts/jquery.ui.button.js"></script>
<script type="text/javascript" src="scripts/jquery.ui.draggable.js"></script>
<script type="text/javascript" src="scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="scripts/jquery.ui.dialog.js"></script>
jQuery UI 的外觀幾乎全靠 CSS 撐起來。jquery.ui.all.css 內部又匯入了大量其他樣式檔,因此建議直接把 development-bundle 裡 themes/base 整個資料夾複製過來,再單獨引入:
<link type="text/css" href="styles/jquery.ui.all.css" rel="stylesheet" />
此時在 ready 中呼叫一次 .dialog(),打開頁面就能看到浮層:
$(function() {
$("#btn").click(function() {
alert("btn 被點擊啦!");
});
// 初始化對話框
$("#dialog-confirm").dialog();
});
多數情境下我們不希望頁面一載入就跳出對話框,需要兩個動作。
第一步,讓容器預設隱藏:
<div id="dialog-confirm" title="Empty the recycle bin?" style="display: none">
...
</div>
第二步,初始化時傳入 autoOpen: false,只做初始化不顯示:
$("#dialog-confirm").dialog({
autoOpen: false
});
最後在點擊事件裡用字串參數 "open" 叫它出來,傳 "close" 則關閉:
$("#btn").click(function() {
$("#dialog-confirm").dialog("open");
});
Web 上沒有真正的系統級模態視窗,jQuery UI 的做法是鋪一層遮罩把背後的元素擋住,讓使用者無法誤點。只要多帶一個 modal: true:
$("#dialog-confirm").dialog({
modal: true, // 建立模態對話框
autoOpen: false // 只初始化,不顯示
});
buttons 選項接受一個物件,鍵是按鈕文字,值是點擊後要執行的函式。在函式內用 $(this) 就能拿到對話框本身,實務上通常一顆負責關閉、一顆負責送出請求:
$("#dialog-confirm").dialog({
modal: true,
autoOpen: false,
buttons: {
"Ok": function() {
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
把 Ok 的內容換成真正的刪除邏輯(例如一波 $.post),就得到一個堪用的確認流程了。