我正在尝试在Javascript中创建谚语测验作为我的第一个“从头开始”练习。这是我的fiddle,其中包含所有其他代码。
这是我的问题:
var allQuestions = [{
"question": "Who was Luke's gunner in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0
}];
在这个函数中,我包含了应该通过单选按钮和用户选择的循环。见下文。
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var answer = 0;
var playerTally = 0;
var playerFeedback = "";
var playerMessage = document.getElementById("playerMessage");
现在我对此感到困惑; 匹配数组中的正确答案,用户在单选按钮中选择的内容,然后动态显示分数。
现在,我可以显示0,但没有增量。
var radioValue = $("input[type='radio'].radioButtons:checked").val();
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
for(i = 0; i < radioValue.length; i++) {
if(radioValue[i].checked) {
if(radioValue[i].value == itemAnswers.correctAnswer) {
playerTally++;
break;
}
}
}
playerFeedback += "<h4>" + playerTally + "</h4> <br/>";
playerMessage.innerHTML = playerFeedback;
}
我不反对使用jQuery的解决方案,但更喜欢使用vanilla JS替代方案,这样我才能真正看到发生了什么!
提前谢谢大家!
答案 0 :(得分:0)
在您进入下一个问题之前,您可以通过
确定答案是否正确if (document.querySelectorAll("#responses input")[allQuestions[currentQuestion].correctAnswer].checked)
答案 1 :(得分:0)
完整的解决方案是
var radios = document.querySelectorAll("#responses input");
var correct = allQuestions[currentAnswer].correctAnswer;
if (radios[correct].checked) {
playerTally++;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
现在我仔细观察它与我的先生
相同