首页 > 解决方案 > 使用回调时如何让 JavaScript 等待用户输入?

问题描述

我正在使用棋盘制作国际象棋游戏。Chessground 仅提供棋盘/棋子动画,不提供国际象棋的实际逻辑(或您想要实现的任何类似国际象棋的游戏)。但是,可以在棋盘上进行任何移动后触发功能。

我要实现的一项功能是典当促销。移动后,我想检查棋子是否在后排,询问用户他们想要提升的棋子,并将棋子传递给负责棋盘逻辑的其他函数。

我的代码看起来像这样:

function specialChessgroundFunctionInvokedUponMove(){

    // previous logic & work omitted 

    promopiece = null

    if (black_is_promoting) {
    
    promoModal("black", function(results) { //promoModal gives the user options
        promopiece = results;

        restOfLogic(promopiece, move, orig, dest);    
    });

    restOfLogic(promopiece, move, orig, dest); 

}

function promoModal(color, callback){
    // Modal dialog box for user to select promoted piece

    var modal = document.getElementById("promo-modal");

    // activate modal box

    modal.style.display = "block";

    // detect which piece was selected and close the box
    $(document).ready(function() {
        $('#modal-container div').click(function() {
            modal.style.display = "none";
            callback(this.id);
        });
    });
};

但是,Javascript 不会等待用户选择作品。相反,会弹出对话框,并立即继续执行,并promopiece具有 value null

我在这里做错了什么,我该如何解决?

标签: javascriptjquery

解决方案


推荐阅读