dialog回りのロジックをjQueryのプラグイン化しておく。
jquery.dialog.js
(function( $ ){
$.alert = function(message) {
var dfd = $.Deferred();
// ダイアログを作成
var dlg = $( "<div></div>" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
dfd.resolve();
}
}
});
dlg.html(message);
return dfd.promise();
};
$.confirm = function(message) {
var dfd = $.Deferred();
// ダイアログを作成
var dlg = $( "<div></div>" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
dfd.resolve("yes");
},
"キャンセル": function(event, ui) {
$( this ).dialog( "close" );
dfd.resolve("cancel");
}
}
});
dlg.html(message);
return dfd.promise();
};
})( jQuery );
index.html
<html>
<title>サンプル</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/start/jquery-ui.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="jquery.dialog.js"></script>
<script type="text/javascript">
(function(){
window.old_alert = window.alter;
window.alter = function(message) {
$.alter(message);
}
window.confirm = function(message, okCallback) {
$.confirm(message)
.then(function(status) {
var ret = (status === "yes");
if(ret)
okCallback();
}) ;
}
})();
$(function(){
$("#button").click(function(e){
$.alert("AlertTest");
});
$("#button2").click(function(){
confirm("やめますか?", function() {
alert("OKがおされました。");
});
});
});
</script>
<body>
<button id="button">alert表示</button>
<div id="alert"></div>
<button id="button2">conform表示</button>
<div id="conform"></div>
</body>
</html>
こんな感じで書いてみたけど、
もともとのwindow.confirmを使っていたところのロジックを少し直さないとだめだから、
できれば、$.confirm()の戻り値でtrue,falseを返せるとベストなんだけど。。。