近來在客戶端用到對話框,順便把 jQuery UI 的 Dialog 元件好好研究了一下,以下把學習成果整理成step-by-step的說明。
先建立一個觸發按鈕:
<input type="button" value="刪除" id="btn" />
並且在 ready 中綁定點擊事件:
<script type="text/javascript" src="scripts/jquery-1.4.2.js"></script>
<script>
$(function() {
$("#btn").click(function() {
alert("btn 被點擊啦!");
}
);
}
</script>
<div id="dialog-confirm" title="Empty the recycle bin?" style="display: none">
<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>
使用 jQuery UI 的對話框需引入相關 js 檔(core、widget、mouse、button、draggable、position、dialog)以及樣式;注意 jquery.ui.all.css 會引用大量其他樣式檔,需把 themes/base 資料夾內容一起複製過來:
<link type="text/css" href="styles/jquery.ui.all.css" rel="stylesheet" />
透過 autoOpen: false 讓對話框初始只初始化不顯示,點擊按鈕時再 open:
$("#dialog-confirm").dialog({ autoOpen: false });
$("#btn").click(function() {
$("#dialog-confirm").dialog("open");
});
$("#dialog-confirm").dialog({
modal: true, // 建立模式對話框
autoOpen: false, // 只初始化,不顯示
buttons: {
"Ok": function() {
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
加上 modal: true 會產生遮罩層擋住底層元素,模擬模式效果;buttons 設定則能自訂對話框的按鈕與各自的事件處理。傳入 close 即可關閉對話框。