简体   繁体   English

何时显示对 TextContent 的更改?

[英]When does a change to TextContent get displayed?

I'm working on Rock/Paper/Scissors game for the Odin Project.我正在为 Odin Project 开发 Rock/Paper/Scissors 游戏。 I display the result of a game in a div resultMsg, and a running tally based on that result in countMsg.我在 div resultMsg 中显示游戏结果,并在 countMsg 中显示基于该结果的运行计数。 Both those items are divs in the HTML and they work correctly.这两个项目都是 HTML 中的 div,它们可以正常工作。 After a total of 5 games are won or lost, I want to (in order) clear the textContent messages, use an "alert" to give a final tally, and start over.在总共赢或输了 5 场比赛后,我想(按顺序)清除 textContent 消息,使用“警报”给出最终计数,然后重新开始。

I expected that the two lines highlighted with "->" would clear the textContent message.我希望用“->”突出显示的两行会清除 textContent 消息。 However they do not until after I click [OK] to clear the alert.但是,直到我单击 [确定] 清除警报后,它们才会这样做。 I'd really like to understand why that is.我真的很想知道为什么会这样。

The HTML relevant body: HTML 相关正文:

    <div id="playersChoice">
        <button id='rock'>Rock</button>
        <button id='paper'>Paper</button>
        <button id='scissors'>Scissors</button>
    </div>    
    
    <div id="result">
    </div>

    <div id="count">
    </div>

The Javascript that's relevant.相关的 Javascript。

let gamesPlayed = 0;
let playerWon = 0;
let computerWon = 0;
const countMsg = document.querySelector ('#count');
const resultMsg = document.querySelector ('#result');

// Get all the buttons within playerschoice container
const userButton = document.querySelectorAll ('#playersChoice > button');

// For each button, create an event listener for the click which will play a round.
// Note the Button.ID identifies the players choice.
userButton.forEach(button => {
    button.addEventListener('click', function() {
        gamesPlayed++;
        resultMsg.textContent = playRound(button.id, computerPlay());

        // if there are less than 5 clear wins or losses
        if ((playerWon + computerWon) < 5) {
            countMsg.textContent = "The current tally is your " + playerWon + " wins to the computers " + computerWon + ".";
        } else {
            // there have been 5 definitive games, declare the overall winner!
->          resultMsg.textContent = '';
->          countMsg.textContent = '';
            gamesPlayed = 0;
            playerWon = 0;
            computerWon = 0;
            alert("Best of 5 series results : You won " + playerWon +", lost " + computerWon + ", and tied "+ (5-playerWon-computerWon) + " of them.");
        }
    });
});
'''

alert() will block the current script execution, but it seems to also blocks the DOM update. alert()将阻止当前脚本执行,但它似乎也阻止了 DOM 更新。 That's why even though the assignement to textContent is before the alert, the text is only shown after the alert has been clicked, and the execution has resumed.这就是为什么即使对 textContent 的分配在警报之前,文本也只会在警报被点击后才显示,并且执行已经恢复。

You can use a very small setTimeout to allow the DOM to update before the alert() fires:您可以使用非常小的 setTimeout 来允许 DOM 在alert()触发之前更新:

 const div = document.querySelector("div"); function test1() { div.textContent = "Test without timeout!"; alert("Test1!"); } function test2() { div.textContent = "Test with timeout!"; setTimeout(() => alert("Test2!"), 10); }
 <button onclick="test1()">Test</button> <button onclick="test2()">Test with timeout</button> <h4>Text content:</h4> <div></div>

Edit:编辑:

I researched a bit more, and to be more precise, DOM updates happen only after the script has finished.我进行了更多研究,更准确地说,DOM 更新仅在脚本完成后发生。 Since alert() blocks the current script, the DOM update will only happen after the alert has been dismissed.由于alert()会阻止当前脚本,因此 DOM 更新只会在警报解除后发生。

This behavior can also be seen with the following snippet:通过以下代码段也可以看到此行为:

 function wait(ms) { var start = Date.now(), now = start; while (now - start < ms) { now = Date.now(); } } function test() { document.querySelector("div").textContent = "Test with delay!"; wait(2000); }
 <button onclick="test()">Test with delay</button> <div></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM