我多年来一直在做一个简单的DOM游戏。而且我无法弄清楚范围为何如此。解释在下面的代码中。我不明白为什么必须在if
语句中的函数内部声明一个var才能起作用,而不是全局范围。我现在已经处理了好几个小时,我知道它一定很简单,但是现在它让我发疯。
//this code does not work - if the var currentScore is declared in the global scope
var
activePlayer = 1;
btnRoll = document.querySelector(".btn-roll");
diceImage = document.querySelector(".dice");
diceImage.style.display="none";
//var currentScore selects a div - either the one from player 1 or 2
currentScore = document.querySelector("#current-" + activePlayer);
btnRoll.addEventListener ("click", function(){
//after clicking roll dice - generate random num
var diceNum = Math.floor(Math.random() * 6) + 1;
diceImage.style.display="block";
//view a correct image that is the generated number
diceImage.src="dice-" + diceNum + ".png";
//if the rolled number greater than one - add to the roundScore
if (diceNum !== 1) {
roundScore += diceNum;
//this below should change the text of 0 of a div for player 1 to text of the round score -which it does
currentScore.textContent = roundScore;
}
//else its other players round
else {
roundScore = 0;
if(activePlayer === 1) {
activePlayer = 2;
//when I console.log the active player it changes to 2
}
else {
activePlayer = 1;
}
}
});
//problem comes when its suppose to start again - it does recognize that its player 2 but the currentScore variable is stil #current-1 instead of #current-2.
要使其正常工作,currentScore
var必须以相同的方式声明,但不能在全局范围内声明,而应在第一个if
语句中声明。为什么?