【发布时间】:2016-06-29 10:45:58
【问题描述】:
我正在编写一个使用单选按钮的多项选择测验脚本。 I wanted to add a feature where when the radio button is selected it checks that if correct answer is chosen then the chose radio button is highlighted green.如果选择了错误答案,则所选单选按钮突出显示为红色,并且正确答案突出显示为绿色。然后启用提交按钮。
当我单击提交按钮时,它会转到下一个问题并重复该过程,直到测验结束。问题是突出显示仅在单击提交按钮后才起作用。并且测验从第二个问题停止工作。我该如何解决?我在下面包含了 jsfiddle 和代码。有人可以帮忙吗?
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["What is 10 + 4?", "12", "14", "16", "B"],
["What is 20 - 9?", "7", "13", "11", "C"],
["What is 7 x 3?", "21", "24", "25", "A"],
["What is 8 / 2?", "10", "2", "4", "C"]
];
function _(x) {
return document.getElementById(x);
}
function renderQuestion() {
test = _("test");
if (pos >= questions.length) {
test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " questions correct</h2>";
_("test_status").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
_("test_status").innerHTML = "Question " + (pos + 1) + " of " + questions.length;
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "<h3>" + question + "</h3>";
test.innerHTML += "<input type='radio' class='choice' name='choices' value='A'id='choA'> <label for='choA'>" + chA + "</label><br>";
test.innerHTML += "<input type='radio' class='choice' name='choices' value='B'id='choB'> <label for='choB'>" + chB + "</label><br>";
test.innerHTML += "<input type='radio' class='choice' name='choices' value='C'id='choC'> <label for='choC'>" + chC + "</label><br>";
test.innerHTML += "<button onclick='checkAnswer()' disabled='disabled' id='choiceSubmit'>Submit Answer</button>";
}
function checkAnswer() {
debugger;
if ($("#test input:checked").val() == questions[pos][4]) {
// correct question clicked
$("#test input:checked+label").css("background-color", "green");
correct++;
}
else {
// wrong question clicked
$("#test input:checked+label").css("background-color", "red");
}
setTimeout(function () {
pos++;
renderQuestion();
}, 1000);
}
$("document").ready(function () {
renderQuestion();
var choiceClicked = false;
if (!choiceClicked) {
$("#test input").change(function () {
choiceClicked = true;
$("#choiceSubmit").removeAttr("disabled");
});
}
});
【问题讨论】:
-
我认为这不是一个非常严肃的测验?因为聪明/精通技术的用户可以通过在页面上查看源代码来轻松作弊
-
请记住,通过在单击提交按钮之前显示突出显示,用户可以按下答案,如果看到那是红色=错误,则可以选择正确答案然后按下按钮。
标签: javascript jquery