需要帮助使用JavaScript

时间:2012-08-01 04:29:58

标签: javascript

我创建了这个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>

3 个答案:

答案 0 :(得分:1)

您可以使用全局跟踪状态。但是,这种安全性很弱,因为用户可以简单地重新加载页面以规避限制。你真正需要做的是在服务器端跟踪状态(例如数据库),然后使用例如数据库。浏览器上的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);"

答案 1 :(得分:0)

一种方法是将生成的数字放入隐藏的元素中。保持计数的次数,当用户正确或尝试4次时,显示值以及他们是否猜对了。也许还会显示尝试次数。

包含重置按钮以重置计数器并生成新的隐藏值。

答案 2 :(得分:0)

为什么不尝试使用prompt()功能,而不是使用文本字段?以下是控制流程的基本概念:

  1. 生成随机数并将其存储在变量中。
  2. 创建一些变量,例如正确并将其设置为false。
  3. 提示用户猜测for loop(4次迭代)
  4. 每次猜测后,检查猜测是否与您存储的号码相符。如果是,则在将更正设置为true后,break提前退出循环。
  5. 退出for循环后,根据正确的值,alert用户是赢还是输。