[英]How can I prevent IF statement from running once the condition is met
I'm making a game where players have to input numbers to guess the population of a country, but I'm having issues counting their scores.我正在制作一个游戏,玩家必须输入数字来猜测一个国家的人口,但我在计算他们的分数时遇到了问题。 I have this if statement:
我有这个 if 语句:
if (player1 === "" || player2 === "") {
resultSpan.innerHTML = "One or two empty values";
} else {
resultSpan.innerHTML = `The correct number is ${population.toLocaleString()}`;
let playerWin = document.querySelector(".results-player-win");
if (
Math.abs(parseInt(population) - playerOneTotal) <
Math.abs(parseInt(population) - playerTwoTotal)
) {
playerWin.innerText = "Player 1 wins!";
playerOneScore++;
}
if (
Math.abs(parseInt(population) - playerOneTotal) >
Math.abs(parseInt(population) - playerTwoTotal)
) {
playerWin.innerText = "Player 2 wins!";
playerTwoScore++;
}
document.getElementById(
"current-score"
).innerHTML = `P1: ${playerOneScore} --- P2: ${playerTwoScore}`;
}
But, instead of incrementing the score by 1, sometimes it's two or three.但是,有时不是将分数增加 1,而是 2 或 3。 I'm guessing this is because another
eventListener
is being called beforehand.我猜这是因为预先调用了另一个
eventListener
。 However, I can't find a way to separate them completely, as they both need to use the same population variable for the score to be calculated correctly.但是,我找不到将它们完全分开的方法,因为它们都需要使用相同的总体变量才能正确计算分数。
I've tried adding this.remove()
inside of the IF statements, but it deletes the button.我试过在 IF 语句中添加
this.remove()
,但它删除了按钮。 I've also tried e.stopImmediatePropagation();
我也试过
e.stopImmediatePropagation();
and creating a variable isFirst
, and setting to true then false, but they block the code completely on second execution.并创建一个变量
isFirst
,然后设置为 true 然后 false,但是它们在第二次执行时完全阻止了代码。
For more clarity, I'm also posting a JSFiddle .为了更清楚,我还发布了一个JSFiddle 。
I managed to fix the issue by initializing the variables我设法通过初始化变量来解决这个问题
playerOneScore = 0;
playerTwoScore = 0
; ; (the ones that track the score) in the global environment.
(跟踪分数的那些)在全球环境中。 I also added
{ once: true }
to the listener that tracks user input/scores as clicking the button multiple times would cause unwanted behaviour.我还将
{ once: true }
添加到跟踪用户输入/分数的侦听器中,因为多次单击按钮会导致不必要的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.