嗯,这可行。
你的对话框函数... showDialog()
function confirmation(question) {
var defer = $.Deferred();
$('<div></div>')
.html(question)
.dialog({
autoOpen: true,
modal: true,
title: 'Confirmation',
buttons: {
"Yes": function () {
defer.resolve(true); //answer
$(this).dialog("close");
},
"No": function () {
defer.resolve(false); //answer
$(this).dialog("close");
}
},
close: function () {
$(this).remove(); //removes this dialog div from DOM
}
});
return defer.promise();
}
然后是使用该函数的代码...
function onclick(){
var question = "Do you want to start a war?";
confirmation(question).then(function (answer) {
if (answer) {
alert("this is obviously " + answer);//TRUE
} else {
alert("and then there is " + answer);//FALSE
}
});
}
对于大多数人来说,这似乎是错误的。但总有一些情况,如果不从 JQuery Dialog 返回就无法进行。
这基本上模仿了confirm()函数。但代码丑陋,确认框看起来不错:)
我希望这可以帮助一些人。
**
编辑:Bootstrap 3 解决方案
**
I am now using [NakuPanda's][1] bootstrap library, It works really well. Basically the same as with JQueryUI but in the Bootstrap UI.
function bsConfirm(question) {
var defer = $.Deferred();
BootstrapDialog.show({
type: BootstrapDialog.TYPE_PRIMARY,
title: 'Confirmation',
message: question,
closeByBackdrop: false,
closeByKeyboard: false,
draggable: true,
buttons: [{
label: 'Yes',
action: function (dialog) {
defer.resolve(true);
dialog.close();
}
}, {
label: 'No',
action: function (dialog) {
defer.resolve(false);
dialog.close();
}
}],
close: function (dialog) {
dialog.remove();
}
});
return defer.promise();
}
function bsAlert(error, message) {
BootstrapDialog.show({
type: error ? BootstrapDialog.TYPE_DANGER : BootstrapDialog.TYPE_SUCCESS,
title: error ? "Error" : "Success",
message: message,
closeByBackdrop: false,
closeByKeyboard: false,
draggable: true,
buttons: [{
label: 'OK',
action: function (d) {
d.close();
}
}]
});
}
并使用它(几乎相同的方式)
bsConfirm("Are you sure Bootstrap is what you wanted?").then(function (answer) {
if (answer) {
bsAlert("Well done! You have made the right choice");
} else {
bsAlert("I don't like you!");
}
});