我正在使用jQuery UI Dialog调用一个确认框,如下所示:
function tps_show_confirm(cTitle, cContent, noClose = true, dwidth = 300, callback=null) {
if (noClose == true) {
var dClass = 'no-close';
} else {
var dClass = '';
}
var confirmDiv = '<div class="tps-confirm-modal">'+cContent+'</div>';
var maxHeight = window.innerHeight * .80;
$( confirmDiv ).dialog({
title: cTitle,
dialogClass: dClass,
modal: true,
width: dwidth,
maxHeight: maxHeight,
draggable: false,
resizable: false,
create: function(event, ui) {
$('body').css({ overflow: 'hidden' })
},
beforeClose: function(event, ui) {
$('body').css({ overflow: 'inherit' })
},
buttons: {
Ok: function() {
if (typeof callback === 'function') {
callback();
}
$( this ).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
}
我试图找出如何在单击“确定”按钮时延迟.dialog('close')
操作,直到回调()函数完成。我已经尝试了.done()和/或.finish()和.when()的各种组合,但我不太了解这些,他们似乎不适合这种情况。< / p>
任何想法如何实现这一目标?
答案 0 :(得分:2)
希望jquery.when有用
Ok: function() {
if (typeof callback === 'function') {
$.when(callback()).then(function() {
$(this).dialog('close');
}.bind(this));
}else{
$( this ).dialog('close');
}
}
此代码段非常有用。我正在传递一个回调函数。在一个回调函数中有一个异步调用。现在当你点击ok
按钮时,回调函数将开始执行,但只有当异步响应时才会关闭对话框操作
function tps_show_confirm(callback = null) {
var confirmDiv = '<div class="tps-confirm-modal">Hello Test</div>';
var maxHeight = window.innerHeight * .80;
$(confirmDiv).dialog({
title: 'test',
dialogClass: 'dClass',
modal: true,
width: 300,
maxHeight: 300,
draggable: false,
resizable: false,
create: function(event, ui) {
$('body').css({
overflow: 'hidden'
})
},
beforeClose: function(event, ui) {
$('body').css({
overflow: 'inherit'
})
},
buttons: {
Ok: function() {
if (typeof callback === 'function') {
$.when(callback()).then(function(data) {
console.log(data)
$(this).dialog('close');
}.bind(this));
} else {
$(this).dialog('close');
}
},
Cancel: function() {
$(this).dialog('close');
}
}
});
}
function test() {
var root = 'https://jsonplaceholder.typicode.com';
return $.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
return data;
});
}
tps_show_confirm(test)
&#13;
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
&#13;