【问题标题】:Change an image using jquery使用 jquery 更改图像
【发布时间】:2015-02-08 03:53:36
【问题描述】:

我有一个刽子手游戏,如果有人猜出不正确的字母,它会添加图像更改。为了做到这一点,我创建了一个变量,当猜到一个不正确的字母时,它会递增,我使用 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("");

}

【问题讨论】:

  • 您能添加更多代码吗? posArray 之前的那个
  • 你有点击事件处理程序吗...如果有,怎么样

标签: javascript jquery


【解决方案1】:

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

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

因为每次调用 CheckGuess() 函数时,它都会重置为零,如果用户失败,它只会递增到 1。这就是您看到相同图像的原因(第一次)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2010-10-07
    • 2011-06-02
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多