问题在于浏览器处理自己的警报、确认和提示与自行生成的对话框的方式。您需要添加 try/catch 类型的场景。
我创建了以下内容来解决这个问题:https://jsfiddle.net/Twisty/7kp46r22/3/ https://jsfiddle.net/Twisty/7kp46r22/3/
这使用$.deferred()
and $.when()
在返回结果或执行任何回调之前等待用户做出选择。
对于您的应用程序,这可能如下所示:
工作示例:https://jsfiddle.net/Twisty/wtogu9cu/ https://jsfiddle.net/Twisty/wtogu9cu/
HTML
<form id="myForm">
Submit Form:
<button type="submit">Go</button>
</form>
jQuery
function ui_confirm(message, callback) {
var dfd = $.Deferred();
var dialog = $("<div>", {
id: "confirm"
})
.html(message)
.appendTo($("body"))
.data("selection", false)
.dialog({
autoOpen: false,
resizable: false,
title: 'Confirm',
zIndex: 99999999,
modal: true,
buttons: [{
text: "Yes",
click: function() {
$(this).dialog("close");
dfd.resolve(true);
if ($.isFunction(callback)) {
callback.apply();
}
}
}, {
text: "No",
click: function() {
$(this).dialog("close");
dfd.resolve(false);
}
}],
close: function(event, ui) {
$('#confirm').remove();
}
});
dialog.dialog("open");
return dfd.promise();
}
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
// your code
$.when(ui_confirm("Are you sure?")).done(function(val) {
if (val) {
console.log("Submit the form.");
$('#myForm')[0].submit();
} else {
console.log("Do not submit the form.");
}
});
});
});
查看更多:
- https://api.jquery.com/category/deferred-object/ https://api.jquery.com/category/deferred-object/
- https://api.jquery.com/jQuery.Deferred/ https://api.jquery.com/jQuery.Deferred/
- https://api.jquery.com/jQuery.when/ https://api.jquery.com/jQuery.when/