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