在javascript中的猜字游戏

时间:2017-02-04 04:19:00

标签: javascript html getelementbyid

我无法弄清楚我在这里做错了什么。我无法获得在我的页面上更新的值(胜利,损失等)。我的所有ID都已在我的HTML中正确设置。任何帮助将不胜感激!

var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l',
    'm','n','o','p','q','r','s','t','u','v','w','x','y','z'];

// Variables for tracking our wins, losses and ties. They begin at 0.
var wins = 0;
var losses = 0;
var guesses = 10;

    var computerChoice = alphabet[Math.floor(Math.random() * alphabet.length)];

    console.log(computerChoice)



   // When the user presses a key, it will run the following function...
document.onkeypress = function(event) {
    var userGuess = event.key;

    if(userGuess === computerChoice){
        wins++;
    }else{
        guesses--;
    }

    if(guesses = 0){
        losses++
    }
}   
    document.getElementById('wins').innerHTML = "Wins: " + wins;
    document.getElementById('losses').innerHTML = "losses: " + losses;
    document.getElementById('guesses').innerHTML = "Guesses left: " + guesses;

1 个答案:

答案 0 :(得分:2)

在更新innerHTML之前,您正在关闭onkeypress函数,因此不会在每个按键上更新它们。我已将结束括号移到html更新部分下方 - 看看是否有效。

我还将最后一个if语句中的赋值运算符更改为严格相等比较运算符,以便可以将猜测计数与0进行比较。

document.onkeypress = function(event) {
    var userGuess = event.key;

    if(userGuess === computerChoice){
        wins++;
    }else{
        guesses--;
    }

    if(guesses === 0){
        losses++
    }

    document.getElementById('wins').innerHTML = "Wins: " + wins;
    document.getElementById('losses').innerHTML = "losses: " + losses;
    document.getElementById('guesses').innerHTML = "Guesses left: " + guesses;

}  // moved to below the innerHTML update