【问题标题】:My code is running before I press the button, can anybody tell me why? [duplicate]在我按下按钮之前我的代码正在运行,有人可以告诉我为什么吗? [复制]
【发布时间】: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,而不是undefinedeverything() === undefinedconsole.log("You started the game.") === undefined。你没有绑定事件监听器。
  • user4642212 对不起,我不是想复制它们。即使在stackoverflow上查找时,我也找不到答案。我想我不擅长查找。

标签: javascript html button onclick


【解决方案1】:

这条线路有问题。

startButton.onclick = console.log("You started the game.")

您在这里要做的是注册一个回调,但您实际上是在调用该函数。

您想要的最小更改是:

startButton.onclick = function(){ console.log("You started the game."); };

这样你就可以让onclick 成为一个在你点击按钮时运行的函数,而不是console.log 的结果。

【讨论】:

  • 感谢您抽出时间来帮助我。
【解决方案2】:
window.addEventListener("click", everything, false) // <= add click event 

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.")

}

【讨论】:

  • 顶部的代码是为了确保程序在窗口加载之前不会运行。我不希望它取代我的按钮的使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多