我在html和javascript中都有此代码 HTML
f
*
我的问题是,当我在文本框中输入正确答案时,correct_ans变量没有添加
答案 0 :(得分:1)
检查正确答案后,应初始化变量result
。
function getResult() {
let correct_ans = 0;
let answer_one = document.getElementById("question_one").value;
if (answer_one === "abuja") correct_ans++;
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
答案 1 :(得分:0)
您在更新变量abuja
之前声明了变量correct_ans
。将其放在if
条件之后。如果您要添加其他问题,则需要将correct_ans = 0
的初始声明放在函数之外,否则您总是会得到0或1。
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
if (answer_one === "abuja") {
correct_ans++;
}
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
答案 2 :(得分:0)
在您的代码中,对结果的评估是在correct_ans增量之前。 试试这个吧。
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "";
if (answer_one === "abuja") {
correct_ans++;
}
result = You answered " + correct_ans + " correctly.
document.getElementById("result").innerHTML = result;
}