简体   繁体   English

javascript不更新p标签的文本

[英]javascript not updating the text of p tag

I have made a simple game using html , css and javascript . 我使用htmlcssjavascript制作了一个简单的游戏。 Image of the game interface is shown below 游戏界面的图像如下所示 在此处输入图片说明

Working of this game 这个游戏的工作

In this game, each player, on his turn, rolls the dice. 在这个游戏中,每个玩家轮流掷骰子。 The number on the dice gets added to current player's current score . 骰子上的数字被添加到当前玩家的current score Each player rolls dice until dice rolls to 1 or if the player clicks on hold score label. 每个玩家掷骰子,直到骰子掷至1或单击hold score标签。

If dice rolls to 1 , current player's current score becomes 0 . 如果骰子滚到1 ,则当前玩家的current score变为0 During his turn, any player can choose to hold score which will add that player's current score to his total score , displayed above the current score , and the then next player takes his turn. 在回合中,任何玩家都可以选择hold score ,该hold score会将该玩家的current score添加到其total score ,并显示在current score之上,然后下一个玩家进行回合。

First player whose total score becomes equal to or greater than 100 , wins. 总分等于或大于100第一位玩家获胜。 Any player's victory is indicated by alert method of javascript . javascriptalert方法表示任何玩家的胜利。

Problem 问题

Example case : 示例案例:

Consider a case where player 1 's total score is 95 and then player 1 rolls the dice and the dice rolls to 5 . 考虑一种情况, player 1total score 95 ,然后player 1投掷骰子,骰子投掷为5 Now player 1 chooses to hold score , so player 1 's total score and current score should add up and the total score should become 100 and then the alert is generated indicating that player 1 has won . 现在, player 1选择hold score ,因此player 1total scorecurrent score应加起来, total score应变为100 ,然后生成警报,表明player 1 has won Problem is that, when any player's total score gets equal or greater than 100 , alert is generated correctly but before generating the alert, that player's total score should update which doesn't happens. 问题是,当任何玩家的总得分等于或大于100 ,会正确生成警报,但是在生成警报之前,该玩家的total score应该更新,这不会发生。

PS. PS。 When the total score is not greater than or equal to 100 for any player, that player's total score updates without any problem. 当任何球员的total score不大于或等于100时,该球员的total score更新而不会出现任何问题。 Problem only seem to arise when total score becomes greater than or equal to 100 仅当total score大于或等于100时才会出现问题

Need help to identify what's causing this issue. 需要帮助来确定导致此问题的原因。

Following code is responsible for updating each player's total score when player chooses to hold score 当玩家选择hold score时,以下代码负责更新每个玩家的总hold score

document.getElementById('hold-score-label').onclick = function () {

    //take current score and add it to total score of current player
    var playerTotalScore = document.getElementById('player'+playerTurn+'-dice-roll-score');
    playerTotalScore.textContent = currentScoreVal + parseInt(playerTotalScore.textContent);

    //set current score of current player to zero
    document.getElementById('p'+playerTurn+'-current-score-value').textContent = 0;

    //CHECK IF ANY PLAYER HAS WON
    if(parseInt(playerTotalScore.textContent) >= 100) {
        checkWin(playerTurn);
    }

    //change player turn
    changePlayerTurn();
};

Complete Javascript code 完整的Javascript代码

var playerTurn = 1;   //1 indicates current turn is of player1
var currentScoreVal = 0; //variable to store current score for "hold score" click event

//HIDE THE PLAYER TURN IMAGE OF PLAYER 2
document.getElementById('player2-turn-img').style.display = 'none';

//ADD ACTIVE CLASS TO PLAYER1
document.getElementById('main-container').classList.add('activePlayer1');

//SET CLICK LISTNER FOR 'ROLL DICE' LABEL
document.getElementById('roll-dice-label').onclick = function() {

    var randomNum = Math.floor((Math.random() * 6) + 1);
    document.getElementById('dice-image').src = "Images/dice"+randomNum+".png";
    setScores(randomNum, playerTurn);
};

//FUNCTION THAT UPDATES CURRENT PLAYER'S SCORES
//RANDOM NUMBER GENERATED IN PREVIOUS FUNCTION IS PASSED AS ARGUMENT TO THIS FUNCTION
//CURRENT PLAYER TURN IS ALSO PASSED TO THIS FUNCTION
function setScores (diceNumber , currentPlayer) {

    //GET HTML ELEMENT OF CURRENT SCORE BASED ON CURRENT PLAYER
    var currentScore = document.getElementById('p'+currentPlayer+'-current-score-value');

    //GET HTML ELEMENT OF TOTAL SCORE BASED ON CURRENT PLAYER
    var diceRollScore = document.getElementById('player'+currentPlayer+'-dice-roll-score');

    if(diceNumber > 1) {
        currentScoreVal = parseInt(currentScore.textContent) + diceNumber;
        currentScore.textContent = currentScoreVal;
    }
    else {
        //SET CURRENT SCORE OF CURRENT PLAYER TO ZERO
        currentScore.textContent = 0;

        changePlayerTurn();
    }
}

//FUNCTION TO CHECK IF CURRENT PLAYER'S SCORE IS GREATER THAN 100 OR NOT
function checkWin(currentPlayer) {
    alert('Player '+ currentPlayer +' has won');
    resetGame();
}

//FUNCTION THAT RESETS GAME TO ITS INITIAL STATE
function resetGame() {
    //reset the current player turn indicator image
    document.getElementById('player1-turn-img').style.display = "inline-block";
    document.getElementById('player2-turn-img').style.display = 'none';

    //set dice image to 'dice1.png'
    document.getElementById('dice-image').src = "images/dice1.png";

    //set current scores of both players to zero
    document.getElementById('p1-current-score-value').textContent = 0;
    document.getElementById('p2-current-score-value').textContent = 0;

    //set total score of both players to zero
    document.getElementById('player1-dice-roll-score').textContent = 0;
    document.getElementById('player2-dice-roll-score').textContent = 0;

    //set active player background color to player1 panel
    document.getElementById('main-container').classList.remove('activePlayer2');
    document.getElementById('main-container').classList.add('activePlayer1');
}

//CLICK LISTNER FOR HOLD SCORE LABEL
document.getElementById('hold-score-label').onclick = function () {

    //take current score and add it to total score of current player
    var playerTotalScore = document.getElementById('player'+playerTurn+'-dice-roll-score');playerTotalScore.textContent = currentScoreVal + parseInt(playerTotalScore.textContent);

    //set current score of current player to zero
    document.getElementById('p'+playerTurn+'-current-score-value').textContent = 0;

    //CHECK IF ANY PLAYER HAS WON
    if(parseInt(playerTotalScore.textContent) >= 100) {
        checkWin(playerTurn);
    }

    //change player turn
    changePlayerTurn();
};

//FUNCTION TO CHANGE CURRENT PLAYER TURN
function changePlayerTurn() {
    if(playerTurn === 1) {
        playerTurn = 2;
        document.getElementById('main-container').classList.add('activePlayer2');
        document.getElementById('player1-turn-img').style.display = "none";
        document.getElementById('player2-turn-img').style.display = 'inline-block';
    }
    else {
        playerTurn = 1;
        document.getElementById('main-container').classList.remove('activePlayer2');
        document.getElementById('player1-turn-img').style.display = "inline-block";
        document.getElementById('player2-turn-img').style.display = 'none';
    }
}

You can test this game yourself : codepen 您可以自己测试此游戏: Codepen

Please note that images shown in the interface above wont show. 请注意,上面界面中显示的图像不会显示。 So dice image wont show but it will update score values when you click on roll dice label. 所以骰子图像不会显示,但是当您点击roll dice标签时它将更新得分值。

I believe it is an issue with the alert blocking the main thread, before the page has been updated. 我相信在页面更新之前,警报会阻塞主线程。

To avoid this, try to place the checkWin function call into a window timeout, effectively decoupling the alert showing from the page update. 为避免这种情况,请尝试将checkWin函数调用置于窗口超时中,以有效地将显示的警报与页面更新脱钩。

setTimeout(function(){checkWin(playerTurn)}, 10);

If you used an on-page alert (effectively showing the result in a div that would not block the page update) then you would be able to avoid this issue. 如果您使用了页面提醒(可以在不会阻止页面更新的div中有效显示结果),则可以避免此问题。

It's a matter of timing. 这是时间问题。 Updating the DOM just takes a bit longer then the code which is executed after you set the total score. 更新DOM所花的时间比设置总分数后执行的代码要长一点。 That's why your alert shows nearly the same moment you wait for the DOM update. 因此,您的警报几乎在等待DOM更新的同时显示。

Just use a timeout, then you'll see better what's happening. 只需使用一个超时,然后您将更好地了解正在发生的事情。

function checkWin(currentPlayer) {
    setTimeout(() => {
       alert('Player '+ currentPlayer +' has won');
       resetGame();
    }, 1000);
}

(The alert prevents the re-rendering of your DOM and after the Alert the score is reset immediately, thus you see no changes) (警报会阻止重新呈现您的DOM,警报后分数会立即重置,因此您看不到任何变化)

And FYI: There's a little bug in your game: If you roll your dice and then keep pressing "Hold the score" you'll get the same points every turn. 仅供参考:您的游戏中存在一个小错误:如果您掷骰子,然后持续按“保持得分”,您每回合都会获得相同的积分。

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

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