var allQuestions = [{
question1: "What is 1 + 1?",
choices: ["1", "2", "3", 4],
correctAnswer: ["2"]
}, {
question2: "What is 2 + 2?",
choices: ["6", "2", "3", 4, ],
correctAnswer: ["4"]
}, {
question3: "What is 3 + 3?",
choices: ["3", "6", "9", 12],
correctAnswer: ["6"]
}];
var newArray = shuffleArray(allQuestions);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function appendQuestions(number) {
if (newArray == "undefined" || newArray == "null" || newArray.length == 0) {
document.getElementById("questionForm").innerHTML = "Complete!";
} else {
for (i = 0; i < 4; i++) {
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>")
}
}
}
$(function() {
$("#questionList").empty();
appendQuestions();
newArray.shift();
})
function isCorrectAnswer() {
checkedVal = $("input[type=radio][name=question]:checked").val();
if (checkedVal == newArray[0].correctAnswer) {
alert("Correct!");
} else {
alert("Wrong!");
}
alert(checkedVal);
}
$("#submitButton").click(function() {
isCorrectAnswer();
$("#questionForm").empty();
appendQuestions();
newArray.shift();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<section id='questions'>
<form id="questionForm">
</form>
<div style='clear:both'></div>
<input id='submitButton' type='button' value='Submit'>
</section>
</div>
首先,对不起粘贴的代码量。我不知道我是否错过了一些小错误,或者我只是写错了代码,所以我认为最好发布所有错误。
我正在尝试获取单选按钮的值。在isCorrectAnswer函数中,前两行用于确定当前检查的单选按钮的值。问题是当我提醒单选按钮的值时,它只是说“打开”。我已经搜索了最后一小时试图弄清楚这意味着什么,或者如何修复它并找不到东西。
如果这是一个愚蠢的问题或已经得到回答,我道歉。
答案 0 :(得分:2)
您必须更改此行:
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>");
致:
$("#questionForm").append("<input name='question' type='radio' value='" +
JSON.stringify(newArray[0].correctAnswer[i]) + "' />"+JSON.stringify(newArray[0].choices[i]));
希望这有帮助。