我正在尝试生成用户要回答的随机加法问题。我生成了随机数,但很难接受用户的答案并对其进行验证。请帮忙!我的代码如下:
js: 函数随机数(){ var num1 = document.getElementById("num1"); var num2 = document.getElementById("num2"); num1.innerHTML = Math.floor((Math.random() * 50) + 1); num2.innerHTML = Math.floor((Math.random() * 50) + 1);
function checkMath() {
var num1 = parseInt((document.getElementById("num1")), 10);
var num2 = parseInt((document.getElementById("num2")), 10);
ans = document.forms.problem.answer;
ans.value = num1 + num2;
if (ans == correct) {
alert("woot");
} else {
alert("nope");
}
}
html:
<body onLoad="randomNum();">
<table>
<tr>
<td>
<div id="problem">
<div>
<p id="num1">00</p>
<div class="plus">+</div>
<p id="num2">00</p>
<hr>
<form id="problem"><p><input id="answer" value=""></p>
<input type="button" onclick="checkMath();" value="Check Answer"></form>
</div>
</div>
</td>
最佳答案
您的代码有几个问题。
首先,您实际上并不是在检查答案的值,而是在替换它。
其次,您使用 DOM 元素作为 parseInt 的参数,而不是字符串(您缺少 innerHTML)。
正确的 javascript 应该是:
function randomNum() {
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
num1.innerHTML = Math.floor(Math.random()*50+1);
num2.innerHTML = Math.floor(Math.random()*50+1);
}
function checkMath() {
var num1 = parseInt(document.getElementById("num1").innerHTML, 10);
var num2 = parseInt(document.getElementById("num2").innerHTML, 10);
var answer = parseInt(document.getElementById("answer").value, 10);
if (answer === num1 + num2) {
alert("woot");
} else {
alert(answer + " is incorrect, correct answer is " + (num1+ num2));
}
document.getElementById("answer").value="";
randomNum();
}
我为你创建了一个 jsfiddle,查看这里:http://jsfiddle.net/883fF/
您的 HTML 有点偏离两个,例如,您打开了 table 标签,但您从未关闭它等等。希望对您有所帮助。
关于javascript - js数学答案验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319511/