需要使用javascript的帮助

need help working with javascript

本文关键字:帮助 javascript      更新时间:2024-06-24

我创建了这个javascript,它生成0-20范围内的随机数。我想做的是创建一个文本字段,用户有4次尝试猜测生成的数字。我该怎么做?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form><input name="code" id="code" type="text" value="" ></input>
<script type="text/javascript">
function makeid() {
    return Math.floor(Math.random() * 20)
}
</script>
<input type="button" style="font-size:9pt" value="Generate Code" onclick="document.getElementById('code').value = makeid()">
</input>
</form>
</body>
</html>

您可以使用全局跟踪状态。然而,这样做的安全性很弱,因为用户可以简单地重新加载页面来规避限制。然后,您真正需要做的是跟踪服务器端(例如数据库)的状态,然后使用浏览器上的Ajax调用进行检查:)

<script type="text/javascript">
var count = 0;
function makeid() {
    count++;
    if (count <= 4) {
      return Math.floor(Math.random() * 20);
    }
    alert('Out of attempts');
}
</script>

编辑抱歉,我只回答了你一半的问题。

  <script type="text/javascript">
        var attempts = 0;
        var secretValue = makeid(); // Calculate the secret value once, and don't vary it once page is loaded
        function makeid() {
            return Math.floor(Math.random() * 20);
        }
        function checkId(userValue) {
            if (parseInt(userValue) == secretValue) {
                alert('Correct');
            }
            else {
                attempts++;
                if (attempts <= 4) {
                    alert('Wrong - try again');
                }
                else {
                    alert('Out of attempts');
                }
            }
        }
  </script>

然后将您的点击处理程序更改为

onclick="checkId(document.getElementById('code').value);"
一种方法是将生成的数字放入隐藏的元素中。记录尝试次数,当用户答对或达到4次尝试时,显示值以及他们是否猜对了。也许还显示了尝试的次数。

包括一个重置按钮,用于重置计数器并生成新的隐藏值。

与其使用文本字段,为什么不尝试使用prompt()函数呢?以下是控制流程的基本思想:

  1. 生成随机数并将其存储在变量中
  2. 创建一些变量,如correct,并将其设置为false
  3. 在for循环中提示用户猜测(有4次迭代)
  4. 每次猜测后,检查猜测是否与您存储的号码匹配。如果是,则在将correct设置为true后尽早脱离循环
  5. 退出for循环后,根据correct的值提醒用户他们是赢了还是输了