You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现先显示第一个innerHTML,再显示函数中调用的第二个innerHTML

问题原因

你设置第一个message.innerHTML后,立刻同步执行了buySquare()里的第二个message.innerHTML赋值操作——浏览器还没来得及完成第一个内容的渲染,就被第二个内容覆盖了,所以看不到第一个提示。

解决方案

有两种简单的方法可以解决这个问题:

方法一:利用setTimeout让浏览器先渲染第一个内容

把buySquare()里的提示设置代码放到setTimeout中,哪怕延迟0毫秒,也能让浏览器先完成当前渲染任务,再执行购买提示的赋值:

async function buySquare(currentPlayer) {
    if (currentPlayer === players[0]) {
        // 给浏览器留渲染第一个内容的时间
        setTimeout(() => {
            message.innerHTML = `<p>Would you like to buy ${pieceOne.parentElement.getAttribute('data-type')}`;
        }, 0);
        let input = await getUserInput();
        if (input === 'y') {
            console.log('you have bought this square');
        } else {
            console.log('you have not bought this square');
        }
    }
}

方法二:将movePiece改为异步函数并等待buySquare完成

把movePiece标记为async,调用buySquare时加上await,这样代码会暂停等待购买流程完成,同时浏览器会利用这段间隙渲染第一个提示内容:

async function movePiece() {
    let diceRoll = rollDice();
    if (currentPlayer === players[0]) {
        currentPosition1 += diceRoll;
        if (currentPosition1 >= board.length) {
            currentPosition1 -= board.length;
        }
        let currentSquare = squares[currentPosition1];
        currentSquare.appendChild(pieceOne);
        message.innerHTML = `${players[0]} you are on ${pieceOne.parentElement.getAttribute('data-type')} `;
        if (squareOwned === false) {
            await buySquare(currentPlayer); // 等待购买流程完成
        }
        currentPlayer = players[1];
    } else {
        currentPosition2 += diceRoll;
        if (currentPosition2 >= board.length) {
            currentPosition2 -= board.length;
        }
        let currentSquare = squares[currentPosition2];
        currentSquare.appendChild(pieceTwo);
        currentPlayer = players[0];
        message.innerHTML = `${players[1]} you are on ${pieceTwo.parentElement.getAttribute('data-type')}`;
    }
}

如果你的getUserInput是基于prompt这类同步弹窗,方法一的setTimeout更合适;如果是异步输入组件,方法二的await能同时保证流程顺序和渲染时机。

内容的提问来源于stack exchange,提问作者NovaBrownie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 19:03:37