用户在模态上输入后执行 Javascript 回调

标签 javascript

我正在编写一个游戏,我有一个 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/

相关文章:

javascript - 我无法在本地计算机上运行 D3 代码

javascript - 在不损失质量的情况下裁剪和调整一组图像的大小

javascript - 触发调整大小事件时出了什么问题?

javascript - 将数组压入数组

javascript - 为什么我的计时器不增加数字?

javascript - 使用来自 API 的 JSON 填充数据表

javascript - AngularJS $HTTP.json

javascript - 在表单中设置值

JavaScript 滚动脚本 - 在测试中触发,而不是在开发站点上触发

javascript - 通过 AJAX 调用问题 knockout 自定义验证