我正在尝试在 jquery 中创建一个自定义确认弹出窗口,我制作了一个函数,当请求时使用文本和两个按钮显示自定义警报:确定,取消。:
function showprompt(content){
$("#confirm").css("display","block");
$("#msg").text(content);
}
问题是我如何才能等到按钮单击并返回结果,如果可以则返回 true?我想我需要使用 Promise 和 defer。我该怎么办?
我不喜欢使用带有插件 JQuery UI - 对话框的预创建确认按钮
最佳答案
对于此类功能来说,Promise 是一个好主意(它们不仅仅适用于异步!)。假设 #confirm
中有两个按钮,分别称为 #ok
和 #cancel
。
它看起来是这样的:
function showprompt(content) {
var dfd = $.Deferred();
$('#confirm').css('display','block')
$('#msg').text(content);
$('#confirm')
//turn off any events that were bound to the buttons last
//time you called showprompt()
.off('click.prompt')
//resolve the deferred
.on('click.prompt','#ok',function() { dfd.resolve(); })
//reject the deferred
.on('click.prompt','#cancel',function() { dfd.reject(); });
//return a the deferred's promise
return dfd.promise();
}
然后你可以像这样使用它:
showprompt(content).then(
function() { alert('You clicked ok'); }, //promise resolved
function() { alert('You clicked cancel'); }, //promise rejected
);
关于javascript - 使用 Promise jquery 自定义确认按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34845351/