首页 > 解决方案 > 如何为另一个按钮功能制作点击计数器?

问题描述

我做了一个函数来检查输入数字是否等于 Math.random()。我想创建另一个函数来检查在用户得到正确答案之前单击按钮的次数。

function guess() {
  var x = document.getElementById('this').value;
  var y = Math.floor((Math.random() * 10));

  if (x == y) {
    alert("Nice");
  } //correct answer
  else if (x > y) {
    alert("Lower");
  } else {
    alert("Higher");
  }
}
<body>
  <input type="number" min=1 max=2 id="this">
  <button type="button" onclick="guess()">Check</button>
</body>

我希望看到该数字已完成的尝试次数。

标签: javascriptfunctionbuttononclickcounter

解决方案


考虑到 Nick Parsons 的评论,我将搜索到的号码移出功能。计数器还需要在函数外部定义,并在每次调用时加一。我还更改了您的代码,以便在正确猜测时给出尝试次数。

var y = Math.floor((Math.random() * 10));
var counter = 0;

function guess() {
  var x = document.getElementById('this').value;
  counter += 1;
  
  if (x == y) {
    alert(`Nice. Took you ${counter} attempts`);
  } //correct answer
  else if (x > y) {
    alert("Lower");
  } else {
    alert("Higher");
  }
}
<body>
  <input type="number" min=1 max=10 id="this">
  <button type="button" onclick="guess()"> Check </button>
</body>

max数字输入字段上的也不正确。


推荐阅读