我正在创建一个子手游戏,但是当我运行该程序时,正确的猜测会覆盖自己...
我的函数代码猜测一个字母显示在这里...如何将猜测的字母存储在数组“ letterBoxes”中而不覆盖先前的值?
// Globala variabler
var wordList;
var selectedWord; på
var letterBoxes;
var hangmanImg;
var hangmanImgNr;
var msgElem;
function init() {
var i;
var startGameBtn;
var letterButtons;
wordList =
["BLOMMA","LASTBIL","SOPTUNNA","KÖKSBORD","RADIOAPPARAT","VINTER","SOMMAR","DATORMUS","LEJON","ELEFANTÖRA","JULTOMTE",
"SKOGSHYDDA","BILNUMMER","BLYERTSPENNA","SUDDGUMMI","KLÄDSKÅP","VEDSPIS","LJUSSTAKE","SKRIVBORD","ELDGAFFEL","STEKPANNA",
"KASTRULL","KAFFEBRYGGARE","TALLRIK","SOFFBORD","TRASMATTA","FLYGPLAN","FLYGPLATS","TANGENTBORD"];
hangmanImg = document.getElementById("hangman");
msgElem = document.getElementById("message");
startGameBtn = document.getElementById("startGameBtn");
document.getElementById("startGameBtn").onclick = startGame;
letterButtons =
document.getElementById("letterButtons").getElementsByTagName("button");
for (i = 0; i < letterButtons.length; i++) letterButtons[i].onclick =
guessLetter;//anrop av funktionen guessLetter
} // End init
window.onload = init; // Se till att init aktiveras då sidan är inladdad
function startGame() {
randomWord(selectedWord); //ok
showLetterBoxes(letterBoxes);
hangmanImg = "pics/h1.png"; //byt till h0.png när koden är klar
document.getElementById("hangman").src = hangmanImg;
hangmanImgNr = 0; //ok!
}
funktion skapa slumpat ord OK
function randomWord() {
var wordIndex;
wordIndex = parseInt(Math.random() * 29);
selectedWord = wordList[wordIndex];
alert(selectedWord);
}
function showLetterBoxes() {
var i;
var newCode;
newCode = "";
for (i = 0; i < selectedWord.length; i++) {
newCode += "<span> </span>";
}
document.getElementById("letterBoxes").innerHTML = newCode;
document.getElementById("letterButtons").getElementsByTagName("value").innerHTML;
}
最佳答案
letterBoxes是一个数组。
您不使用+,使用推入功能。
letterBoxes.push("<span>" + letter + "</span >");
和
letterBoxes.push("<span>*</span>");
关于javascript - 将值存储在数组中,而不会覆盖之前的猜测字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43043443/