gpt4 book ai didi

javascript - 使用 jquery 更改图像

转载 作者:行者123 更新时间:2023-11-28 00:45:56 25 4
gpt4 key购买 nike

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

}

最佳答案

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

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

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

关于javascript - 使用 jquery 更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com