这些是我用JavaScript制作数组的类别
var f1teams = [
["F","E", "R", "R", "A", "R", "I"],
["M", "C", "L","A","R","E","N"]
["R","E","D","B","U","L","L"],
["S","A","U","B","E","R"],
["F","O","R","C","E","I","N","D","I","A"],
["R","E","N","A","U","L","T"]
]
var PremierLeague = [
["L","I","V","E", "R", "P", "O", "O", "L"],
["L", "E", "I","C","E","S","T","E","R"]
["A","R","S","E","N","A","L"],
["M","A","N","C","H","E","S","T","E","R","C","I","T","Y"],
]
这是我用来选择类别链接到dropdown
功能setCategory
事件的html onChange
菜单。
<select id ="cards" onchange="setCategory()">
<option value="1" selected="selected">Please select a Category</option>
<option value = "PL">Premier League Football Teams</option>
<option value = "F1">Formula 1 Teams</option>
</select>
这是setCategory函数,其默认值为f1teams。我在函数末尾调用setUnderline()
来相应地设置空白
var selectCat = f1teams.slice();
function setCategory() {
var e = document.getElementById("cards");
var strUser = e.options[e.selectedIndex].value;
if (strUser == "F1") {
window.alert("You have chosen Formula1 as your category");
selectCat = f1teams.slice();
}
else if (strUser == "PL") {
window.alert("You have chosen Premier League as your category");
selectCat = PremierLeague.slice();
}
else {
window.alert("Please choose a category");
selectCat = f1teams.slice();
}
setUnderline();
}
这些是在任何函数之外定义的一些变量,后跟setUnderline函数和启动。
var random = Math.floor((Math.random() * (selectCat.length)));
var letter = selectCat[random];
var underline = new Array(letter.length);
for (var i = 0; i < underline.length; i++){
underline[i] = "_ ";
}
function setUnderline(){
for (var i = 0; i < underline.length; i++){
var guessfield = document.getElementById("guessfield");
var letters = document.createTextNode(underline[i]);
guessfield.appendChild(letters);
}
}
function initiation(){
if (selectCat !== null) {
setUnderline();
}
window.onload = initiation;
然而,当我点击dropdown
菜单更改类别时,它只会形成同一个单词的一些新空白。
更改前:
更改后:
如何制作它以便在不同的类别中为不同的单词制作空白,而不是仅仅在更改类别时为同一单词形成空白。
我的整个代码都在this repo上传,但没有setCategory()函数
答案 0 :(得分:0)
如果我正确理解了问题,那么你就走在了正确的轨道上。
在我看来,您错过了删除guessfield
元素内容的步骤。
这样的步骤可能如下所示:
function setUnderline() {
var guessfield = document.getElementById("guessfield");
// Clear the existing contents of guessfield
guessfield.innerHTML = '';
for (var i = 0; i < underline.length; i++){
var letters = document.createTextNode(underline[i]);
guessfield.appendChild(letters);
}
}