我正在编写一个游戏,我有一个 javascript 函数调用模态来掷骰子,所以我需要停止执行该函数,直到掷骰子结果。我研究了回调和 promise ,但无法将其整理出来以获得我需要的功能。这是我的代码。
function docombat()
{
getplayerroll("1d20","initiative")
}
function getplayerroll(dice,reason)
{
$.ajax({
url: "myurl",
type:"post",
data:{dice:dice,reason:reason},
success: function(newHTML, textStatus, jqXHR)
{
$(newHTML).appendTo('body').modal({
escapeClose: false,
clickClose: false,
showClose: false
});
}
});
//something like wait for the dice to be rolled and keep going
}
然后是模态
<div id="diceroll""></div>
模态JS
function after_roll(res) { diceroll.innerHTML = res; }
所以我需要在原始函数中等待 after_roll()
最佳答案
我假设您使用的是 jQuery Modal从建筑风格来看。在这种情况下,您应该能够使用自定义事件来实现所需的控制流:
function getplayerroll(dice,reason)
{
$.ajax({
url: "myurl",
type:"post",
data:{dice:dice,reason:reason},
success: function(newHTML, textStatus, jqXHR)
{
$(newHTML).appendTo('body').modal({
escapeClose: false,
clickClose: false,
showClose: false
})
// register the event handler
.on('dice-rolled', onDiceRolled);
}
});
//something like wait for the dice to be rolled and keep going
function onDiceRolled(evt)
{
// carry on with the execution here....
}
}
模态JS
function after_roll(res)
{
diceroll.innerHTML = res;
// Trigger the event to activate the continuation
$.modal.getCurrent().$elm.trigger('dice-rolled', { /* stick data here */ });
}
关于用户在模态上输入后执行 Javascript 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847132/