【发布时间】:2020-07-04 19:57:59
【问题描述】:
所以我有一个名为“inGame()”的函数,在创建该函数之后,我让 JavaScript 创建一个带有 onClick-Event 的按钮“inGame()”。但是当我点击按钮时,控制台会告诉我
Uncaught ReferenceError: inGame is not defined at HTMLButtonElement.onclick (index.html:1)
(index.html:1 是<!DOCTYPE html> ...)
这是我正在使用的代码:
var i = 0;
function inGame() {
try {
removeElement("nextPlayer");
} catch (e) {/*First time the function gets called -> Button doesn't exist yet*/}
document.getElementById("title").innerText = players[i] + " ist dran!"; //Just a title, don't worry
rollDice(i);
i++;
if (i == players.length) {i = 0;}
}
inGame();
setTimeout(addElement("game", "button", "nextPlayer", "Nächster Spieler"), 2000);
setTimeout(document.getElementById("nextPlayer").classList.add("btn"), 2000);
setTimeout(document.getElementById("nextPlayer").classList.add("btn-success"), 2000);
setTimeout(document.getElementById("nextPlayer").setAttribute("onClick", "inGame()"), 2000);
顺便说一句:我不使用 for 循环而是使用函数的原因是,我希望循环等到按下按钮以继续下一轮。
编辑: 有关代码的一些一般信息。 我正在使用标准的 html-Framework Visual Studio Code,当您在 emtpy HTML 文件中键入感叹号并按 Enter 键时。
脚本在 head-tag 中,我也尝试将它放在 body 中,但没有任何改变。
我使用的是按钮标签 (<button>),因为 Bootstrap 在其示例中使用了按钮标签。我把它改成了一个 div,但它没有改变任何东西,所以我回到了一个按钮。
这不是我第一次在代码中通过属性添加 onClick 事件。 addElement("content", "button", "Play", "Spielen"); document.getElementById("Play").setAttribute("onclick", "Play()");
这是 addElement-Function:
function addElement(parentId, elementTag, elementId, html) {/*CODE*/}
【问题讨论】:
-
该函数不存在,或者在您调用它时(单击按钮时)它不是全局函数。为什么不能根据提供的示例来解释。我们需要知道 JS 是如何以及在哪里加载到文档中的。
-
@Teemu 我在问题中添加了一些信息,请参阅“编辑:有关代码的一些一般信息”
标签: javascript html onclick