【问题标题】:*SOLVED* How to execute a function after a button is clicked? [closed]*已解决*单击按钮后如何执行功能? [关闭]
【发布时间】:2021-07-06 04:33:44
【问题描述】:

每次单击buttonA 时,我都会尝试从lives 变量中减去1 条生命值。但是removeLives();函数在buttonA被点击之前执行。

<html lang="en">
  <body>
    <div id="lives"></div>
    <button id="buttonA" onClick="removeLives()">buttonA</button>

<script>
  var lives = 3;

  document.getElementById("lives").innerHTML="LIVES: " + removeLives();
  document.getElementById("buttonA").onClick = function(){
    removeLives() {
    lives--;
    return lives;
    }
  }
  </script>
 </body>
</html>

【问题讨论】:

  • 你在加载脚本时调用 removeLives() ?

标签: javascript function button onclick click


【解决方案1】:

当解释器运行.innerHTML="LIVES: " + removeLives();这一行时,removeLives会被调用,导致lives被递减,新的内容减少。

改为将该行放在点击处理程序中,并最初通过 HTML 填充 lives div。

另外,要么在 HTML 中使用内联处理程序,要么在 JS 中使用.onclick,但不能同时使用两者——最好避免使用内联处理程序,因为它们被普遍认为是不好的做法。要在 JS 中添加处理程序,请确保使用 .onclick,而不是 .onClick,它区分大小写。

您可能还想在lives 达到 0 时停止递减。

var lives = 3;
document.getElementById("buttonA").onclick = function() {
  lives--;
  if (lives < 0) lives = 0;
  document.getElementById("lives").innerHTML = "LIVES: " + lives;
};
<div id="lives">LIVES: 3</div>
<button id="buttonA">buttonA</button>

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2020-09-16
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多