【发布时间】:2020-07-27 05:04:08
【问题描述】:
我正在为我的个人网站制作一个基于 javascript 文本的游戏,但我似乎无法弄清楚为什么 我的代码在按下按钮之前正在运行。当我重新加载页面时,代码无需单击按钮即可运行。谁能告诉我为什么?我正在使用香草 javascript。这是代码。
window.addEventListener("load", everything(), false)
function everything() {
var startButton = document.getElementById('Enter');
/*The code below is the code I need to run when I press the Click to start button*/
startButton.onclick = console.log("You started the game.")
}
<h4 id="gameText">Click the button below to play.</h4> <br>
<button id="Enter" width=100px>Click to start</button> <br>
<button id="but1"> /\ </button> <br>
<button id="but2"> | </button> <br>
<button id="but3"> |</button> <br>
【问题讨论】:
-
这部分代码是为了确保没有一个错误是由于JS在HTML加载之前运行造成的。
-
也是“OnClick” events created through JavaScript are triggering immediately, not when the object is clicked 的副本。
addEventListener的第二个参数和onclick的值应该是functions,而不是undefined。everything() === undefined和console.log("You started the game.") === undefined。你没有绑定事件监听器。 -
user4642212 对不起,我不是想复制它们。即使在stackoverflow上查找时,我也找不到答案。我想我不擅长查找。
标签: javascript html button onclick