问题描述
在一个aspx页面中,有一个这样的asp:linkbutton:
In an aspx page, there is an asp:linkbutton like this:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"
OnClientClick="javascript:return confirmExit();"
EnableViewState="false"
OnClick="ExitButtonClick"></asp:LinkButton>
这是javascript函数:
And this is the javascript function:
<script type="text/javascript">
function confirmExit() {
bootbox.confirm("Are you sure?", function (confirmed) {
return confirmed;
});
}
</script>
问题是,据我所知,bootbox.confirm 是异步工作的,后面代码上的 ExitButtonClick 函数是在不等待用户确认的情况下执行的.
The problem is that, as far as I know, bootbox.confirm works asynchronously, and ExitButtonClick function on code behind is executed without waiting for the user confirmation.
我找到了一个有效的解决方案,使用隐藏按钮:
I found a solution that works, using a hidden button:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"></asp:LinkButton>
<asp:Button runat="server" ID="btExitHidden" onclick="ExitButtonClick" style="display:none;" />
这是 javascript 部分:
And this is the javascript part:
<script type="text/javascript">
$("#btExit").click(function (e) {
e.preventDefault();
bootbox.confirm("Are you sure?", function (confirmed) {
if (confirmed) {
$("#btExitHidden").click();
}
});
});
</script>
我的问题是是否有一种更漂亮"和标准"的方式与 Bootbox.confirm 同步工作,而不使用隐藏按钮.
My question is if there is a more "beautiful" and "standard" way to work synchronously with a Bootbox.confirm, without using a hidden button.
推荐答案
您可以通过这种方式制作自定义同步引导箱功能:
You can make a custom sync bootbox function this way:
function ayncBootbox(message, cb = null) { // cb : function
return new Promise(resolve => {
bootbox.confirm({
message: message,
buttons: {
confirm: {
label: "Yes"
},
cancel: {
label: "No"
}
},
callback: cb ? result => cb(resolve, result) : result => resolve(result)
})
})
}
如果你需要做一些额外的事情,你可以通过传递一个自定义回调来调用它
then you can call it this way by passing a custom callback if you need to do some extra stuff
var result = await ayncBootbox("message", (resolve, result) => resolve(result))
或者只是
var result = await ayncBootbox("message")
PS:不要忘记将调用者函数也设为异步 :) 如果需要,您可以使用拒绝来扩展此代码
PS: don't forget to make the caller function as async as well :) and you can extend this code more with reject if needed
这篇关于Bootbox.confirm 可以同步工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!