2017-09-17 61 views
0

值我不明白爲什麼我的代碼不改變它的值我的功能不會改變的變量

let gameIsRunning = false; 

const start = document.getElementById('start-game'); 
start.addEventListener('click', startGame); 

function startGame() { 
    return gameIsRunning = true; 
} 

console.log(gameIsRunning); // still false after click start-game 

其實裏面有稍微的代碼,但我做到了縮短。

回答

2

您需要先登錄start-game元素上的click。從函數中刪除返回部分,並將console.log放入函數中。

let gameIsRunning = false; 
 

 
const start = document.getElementById('start-game'); 
 
start.addEventListener('click', startGame); 
 

 
function startGame() { 
 
    gameIsRunning = true; 
 
    console.log(gameIsRunning); 
 
}
<p id="start-game">Click</p>

+1

噢,我的壞的問題。我確實點擊了開始遊戲元素,但仍然是錯誤的。 –

+0

它正在工作。看例子。也許這不是你的代碼的所有部分 –

+0

是的,我不知道這裏有什麼魔法,在我質疑它之後。有用。謝啦 –