我编写了一个包含一些简单数学问题的代码。当用户按下提交时,if 语句将确定文本框是否为空或有一些输入。我添加了一个 if 语句,如果用户正确回答了问题,则会记录下来。写正确,如果为空,则写未回答,依此类推。相反,无论文本框为空还是答案错误,它都会输出正确的结果。我知道 document.write 不受欢迎,但我是初学者,所以请帮助我。
document.getElementById("q1");
document.getElementById("q2");
document.getElementById("q3");
document.getElementById("q4");
document.getElementById("a1");
document.getElementById("a2");
document.getElementById("a3");
document.getElementById("a4");
document.getElementById("submit");
function check() {
if((q1.value == 6084) || (q1.value == 6,084)){
document.write("<b>" + "1. Correct" + "</b>");
} else if(q1.value.length == 0){
document.write("<b>" + "1. Not Answered" + "</b>");
}
else {
document.write("<b>" + "1. Incorrect" + "</b>");
}
}
<!DOCTYPE html>
<html>
<head>
<title>Quiz1</title>
</head>
<body>
<h1 align = "center">Math Test 📃✍</h1>
<h3 id = "q1">Question 1 : 78 * 78 = ?</h3>
<input id = "a1" type = "text" required>
<h3 id = "q2">Question 2 : (100 / 6) + 45 = ?</h3>
<input id = "a2" type = "text">
<h3 id = "q3">Question 3 : 87 + 123 = ?</h3>
<input id = "a3" type = "text">
<h3 id = "q4">Question 4 : 100 - 23 = ?</h3>
<input id = "a4" type = "text">
<br>
<br>
<button id = "submit" onclick = "check()">I'm Done!</button>
</body>
</html>
最佳答案
尝试此代码
您需要检查从表单中提供的数据的有效性,并计算用户正确给出的答案数量
function check() {
var a1 = document.getElementById("a1").value;
var a2 = document.getElementById("a2").value;
var a3 = document.getElementById("a3").value;
var a4 = document.getElementById("a4").value;
if (isNaN(a1) || a1 == "") {
alert("Please answer question 1 or enter a number value");
} else if (isNaN(a2) || a2 == "") {
alert("Please answer question 2 or enter a number value");
} else if (isNaN(a3) || a3 == "") {
alert("Please answer question 3 or enter a number value");
} else if (isNaN(a4) || a4 == "") {
alert("Please answer question 4 or enter a number value");
} else {
let count = 0;
if (a1 == 6084) {
count++;
}
if (a2 == 61.66) {
count++;
}
if (a3 == 210) {
count++;
}
if (a4 == 77) {
count++;
}
document.write("<h2>You have " + count + " correct answer out of 4 questions</h2>")
}
}
<!DOCTYPE html>
<html>
<head>
<title>Quiz1</title>
</head>
<body>
<h1 align = "center">Math Test 📃✍</h1>
<h3 id = "q1">Question 1 : 78 * 78 = ?</h3>
<input id = "a1" type = "text" required>
<h3 id = "q2">Question 2 : (100 / 6) + 45 = ?</h3>
<input id = "a2" type = "text">
<h3 id = "q3">Question 3 : 87 + 123 = ?</h3>
<input id = "a3" type = "text">
<h3 id = "q4">Question 4 : 100 - 23 = ?</h3>
<input id = "a4" type = "text">
<br>
<br>
<button id = "submit" onclick = "check()">I'm Done!</button>
</body>
</html>
关于javascript - 当我为不同的条件设置不同的 if 语句时,为什么只输出一个 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079820/