我的代码中的startGame函数出现问题,我正在寻求帮助。最初,我有一些像这样的HTML代码:
`
<div id="startScreen">
<h1>Spell and Blade</h1>
<button id="startButton">Start</button>
<!-- Pop-up window -->
<div id="popUpWindow" class="popUpWindow">
<!-- Pop-up window content -->
<div class="popUpWindow-content">
<span class="close">×</span>
<p>
Please select a character type that best fits your play style.
The character type you choose will be the character you control!
</p>
<div id="characterButtons">
<button class="tank" onclick="startGame(1)">Tank</button>
<button class="wizard" onclick="startGame(2)">Wizard</button>
<button class="elf" onclick="startGame(3)">Elf</button>
</div>
</div>
</div>
`
^^此代码嵌入在body标签中,脚本标签位于按钮上。这是HTML页面的主要内容。 在我的javascript标签中调用此函数时,当用户单击任何characterButtons时,它都是未定义的。
Javascript,文件名Canvas.js:
`function startGame(characterType){
//Code that starts the game.
}`
我尝试过的其他解决方案是另一个名为ButtonProperties.js的文件:
characterButtons.onclick = function () {
console.log("Here in characterButton function");
var characterType = 0;
var tankButton = document.getElementsByClassName("tank");
var wizardButton = document.getElementsByClassName("wizard");
var elfButton = document.getElementsByClassName("elf");
if (tankButton.onclick) {
console.log("Here in tankButton if statement");
characterType = 1;
startGame(characterType);
}
if (wizardButton.onclick) {
characterType = 2;
startGame(characterType);
}
if (elfButton.onclick) {
characterType = 3;
startGame(characterType);
}`enter code here`
}
上面的文件也有与弹出窗口相关的代码,但我不认为这也是问题所在 var characterButtons = document.getElementById(“characterButtons”);位于文件顶部附近,上面没有列出。
我对为什么函数没有被调用一无所知。 console.log函数计算单击字符按钮的次数,但程序不会进入任何if语句。任何人都可以提供的帮助非常感谢!
答案 0 :(得分:0)
您正在使用返回数组的getElementsByClassName,因此您的按钮tankButton,wizardButton等是数组。我建议你改变你的代码,如下所示
<div id="characterButtons">
<button id="tank" onclick="startGame(1)">Tank</button>
<button id="wizard" onclick="startGame(2)">Wizard</button>
<button id="elf" onclick="startGame(3)">Elf</button>
</div>
并使用
var tankButton = document.getElementById("tank");
var wizardButton = document.getElementById("wizard");
var elfButton = document.getElementById("elf");
然后它应该工作。这也是更好的表现。