最近我一直在做数学测验以获得乐趣。但是,我试图想出一个计数器来计算用户的正确答案,并在页面底部显示计数。我之前尝试过查找过,但一无所获。
这是我的HTML:
<div>
<p>What is 18 + 4?</p>
<div>
<input type="text" id="lol">
<button id="q1" onclick="lmao()">Answer</button>
</div>
<p id="q1c" class="correct"></p>
<p id="q1i" class="incorrect"></p>
<p>What is 19 + 21?</p>
<div>
<input type="text" id="loll">
<button id="q2" onclick="lmfao()">Answer</button>
</div>
<p id="q2c" class="correct"></p>
<p id="q2i" class="incorrect"></p>
</div>
这是我的JavaScript:
function lmao() {
if (document.getElementById("lol").value == "22") {
document.getElementById("q1c").innerHTML = "Correct!";
alert('Correct');
} else {
document.getElementById("q1i").innerHTML = "Incorrect!";
alert('Incorrect');
}
}
function lmfao() {
if (document.getElementById("loll").value == "40") {
document.getElementById("q2c").innerHTML = "Correct!";
alert('Correct');
} else {
document.getElementById("q2i").innerHTML = "Incorrect!";
alert('Incorrect');
}
}
答案 0 :(得分:0)
如果答案不正确或不正确,您可以将其简化为一个<p>
标记,而不是使用单独的<p>
标记进行标记,只需更新内部文字即可它们,然后我们使用简单的JavaScript表示法来更新字体的颜色:object.style.color = "green"
。这提供了更清晰的HTML。
这是一个工作示例(我删除了所有多余的标签和样式):
var answer1Count = 0;
var answer2Count = 0;
var correctCount = 0;
function answer1() {
var answer = document.getElementById("problem1");
var alert = document.getElementById("problem1Alert");
if (answer.value == "22") {
alert.textContent = "Correct!";
alert.style.color = "green";
correctCount +=1; //update global count of correct answers
answer1Count +=1;
document.getElementById("correctCount").textContent = correctCount;
} else {
if (answer1Count !== 0) {
answer1Count -=1;
correctCount -=1;
document.getElementById("correctCount").textContent = correctCount;
}
alert.textContent = "Incorrect!";
alert.style.color = "Red";
}
}
function answer2() {
var answer = document.getElementById("problem2");
var alert = document.getElementById("problem2Alert");
if (answer.value == "40") {
alert.textContent = "Correct!";
alert.style.color = "green";
answer2Count +=1; //update global count of correct answers
correctCount +=1;
document.getElementById("correctCount").textContent = correctCount;
} else {
if (answer2Count !== 0) {
answer2Count -=1;
correctCount -= 1;
document.getElementById("correctCount").textContent = correctCount;
}
alert.textContent = "Incorrect!";
alert.style.color = "Red";
}
}
&#13;
<p>What is 18 + 4?</p>
<input type="text" id="problem1">
<button onclick="answer1()">Answer</button>
<p id="problem1Alert"></p>
<p>What is 19 + 21?</p>
<input type="text" id="problem2">
<button onclick="answer2()">Answer</button>
<p id="problem2Alert"></p>
<p>Correct Answer Count: <b id="correctCount">0</b></p>
&#13;
我们使用innerHTML
而不是textContent
,而使用纯文本进行更新更安全,更快,因为它不需要解析HTML。您可以轻松搜索SO以了解使用innerHTML
的缺点。
此外,我会不惜一切代价避免使用CSS进行内联样式设置。它使您的代码更难阅读。我建议您将所有样式放在单独的样式表中,并在<head>
标记中包含该样式表,如下所示:
<link rel="stylesheet" href="style.css">