javascript - 如何为另一个按钮功能制作点击计数器?
问题描述
我做了一个函数来检查输入数字是否等于 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>
我希望看到该数字已完成的尝试次数。
解决方案
考虑到 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
数字输入字段上的也不正确。
推荐阅读
- node.js - Node.js - 如何在 MongoDB 中的填充字段上应用过滤器和文本搜索?
- python - 在 python 中使用智能卡在网站上进行身份验证
- sharepoint - SharePoint:每个文档集的特定视图
- database - 为彼此共享大量数据的模型设计数据库表
- angular - 如何在 Angular 8 中使用 tokenNotExpired
- bash - 以给定的行数从 file1 到 file2 交错文本文件
- firebase - 如何使用 Google Interactive Canvas 导入更多屏幕网页
- vuejs2 - 如何为 QTable 操作 JSON 数组
- sql - sql查找两个表之间的差异值
- javascript - 在弹窗JS上监听GET回调