我的目标是编写可提出问题并从用户那里得到答案的Web应用程序,并将其与已知答案进行比较,并告诉他/她答案是否正确。
现在,“问题”是硬编码的HTML(请参见下面的代码)。答案也是JS代码中的硬代码。只有比较发生在JS函数中。
在JS代码中,我已将问题和答案定义为对象。
现在,我希望问题(在HTML网页上显示)和答案动态地来自JS对象。
感觉好像我错了。也许总有更好的方法?
我的HTML代码:
<body>
<link rel="stylesheet" href="./style.css">
<br>
<br>
<h6> What is 2 + 2 ? </h6>
<br>
<form action="PayslipServlet" method="get">
My Answer: <input type="text" name="ans" id="ans"><br/>
<br>
Evaluation of My Answer: <span id="eval"></span>
<br>
<!-- <input type="button" class="button" value="Submit" onClick="check_answer()"> -->
<script type="text/javascript" src="check_answer_v2.js"></script>
<input type="button" class="button" onclick="check_answer()" value="Submit">
</form>
</script>
</body>
我的JavaScript代码(check_answer_v2.js)
var question_answer = {
question: "What is 2 + 2 ?",
answer: "4",
};
function check_answer() {
given_ans = +document.getElementById('ans').value
// document.getElementById("eval").innerHTML = typeof given_ans ;
if (given_ans == 4) {
document.getElementById("eval").innerHTML = 'Correct' ;
} else {
document.getElementById("eval").innerHTML = 'Incorrect' ;
}
}
感谢您的任何帮助!
您没有正确初始化given_ans
变量,因此这是代码中有问题的行:
given_ans = +document.getElementById('ans').value
您无法在其中登录+
:)-而且,您的html中也忘记了</script>
。
var question_answer = {
question: "What is 2 + 2 ?",
answer: "4",
};
function check_answer() {
given_ans = document.getElementById("ans").value;
// document.getElementById("eval").innerHTML = typeof given_ans ;
if (given_ans == 4) {
document.getElementById("eval").innerHTML = "Correct";
} else {
document.getElementById("eval").innerHTML = "Incorrect";
}
}
<h6>What is 2 + 2 ?</h6>
<br />
<form action="PayslipServlet" method="get">
My Answer: <input type="text" name="ans" id="ans" /><br />
<br /> Evaluation of My Answer: <span id="eval"></span>
<br />
<input type="button" class="button" onclick="check_answer()" value="Submit" />
</form>
嗯,您可以使用question_answer.question
访问问题的文本,并将其分配为h6的innerHTML
:
//will execute when the page loads
//so that we are sure the h6 did indeed load.
onload = function() {
document.querySelector('h6').innerHTML = question_answer.question;
}
var question_answer = {
question: "What is 2 + 2 ?",
answer: "4",
};