使用jquery更改图像

时间:2014-12-10 03:18:58

标签: javascript jquery

我有一个刽子手的游戏,如果有人猜到一个不正确的字母,它会添加图像更改。为了实现这一点,我创建了一个变量,当猜到错误的字母时会增加,我使用Jquery .html来更改图片。我遇到的问题是,第一个错误的猜测会改变图片,但随后的猜测却没有。这是因为Jquery的.html只是增加了另一个div吗?对此有什么好的解决方案?以下是代码

var word;
var wrongGuess = 0;
var usedLetters = [];

$(document).ready(function () {
    SetGameBoard();
});

//When guess button is clicked
$('#BtnGuess').click(function () {
    CheckGuess();
});

function GetPhrase() {
    word = ReturnWord();
    alert(word);
}

function SetGameBoard() {
    $('#WinLose').hide();
    $('#controls').show();
    GetPhrase();
    wordToGuess = new Array(word.length);

     // Place underscore for each letter in the answer word in the DivWord div
    for (var i = 0; i < word.length; i++){
       wordToGuess[i] = "_ ";
     }
    $('#DivWord').html(wordToGuess);
}


function CheckGuess() {
    var pos = 0;
    var posArray = [];
    var guessLetter = $('#tbGuessLetter').val();
    var picNum = 0;


    //check to see if letter has been used 
    if(usedLetters.indexOf(guessLetter) != -1){
        alert("You've already used this Letter!");
    }

    //populate array with indices of occurrences of guessed letter
    while ((pos = word.indexOf(guessLetter, pos)) > -1) {
        posArray.push(++pos);
        }

    //if the guessed letter is not in the word...
    if (posArray.length == 0) {
        picNum++;
        alert(guessLetter + " is not in the word.");
        $('#DivPic').html('<img src="images/h'+picNum+'.png" />');



    }else{
        //iterate over array of underscores (wordToGuess[]) and splice in guessed letter
      for(i=0; i < posArray.length; i++){
        wordToGuess.splice(posArray[i] - 1, 1, guessLetter);
       }
        //update DivWord
        $('#DivWord').html(wordToGuess);
        usedLetters.push(guessLetter);
    }
    $('#tbGuessLetter').val("");

}

1 个答案:

答案 0 :(得分:1)

您应该将 picNum 移到顶部,将其声明为全局:

var picNum = 0;
var word;
var wrongGuess = 0;
var usedLetters = [];

因为每次进入CheckGuess()函数它都会重置为零,那么如果用户失败,它只会增加到1.这就是你看到相同图像的原因(第一次)