2017-10-08 90 views
0

我的代码中有一个startGame函数出现问题,我正在寻求帮助。本来,我有一些HTML代码如下所示:Javascript,程序没有输入按钮点击的功能

`

<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">&times;</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标签中调用此函数时未定义。

的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

您正在使用返回数组的getElementsByClassName,因此您的按钮tankBut​​ton,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"); 

那么它应该工作。这也是更好的性能。

+0

工作就像一个魅力!感谢您的帮助!! –