使用此代码,我希望能够使用相同的代码分离问卷,只需要不同的正确答案。
正如您所看到的,我刚尝试在代码阵列上添加另一个答案以进行不同的测验,但它无法识别答案(测试)。这样做的最佳方式是什么?有人告诉我你可以使用传递参数来添加不同的数组吗?
以下是我的全部代码:
// Insert number of questions
var numQues = 4;
// Insert number of choices in each question
var numChoi = 3;
// Insert number of questions displayed in answer area
var answers = new Array(4);
// Insert answers to questions
answers[0] = "Apple", "Test" ;
answers[1] = "Dynamic HTML";
answers[2] = "Netscape";
answers[3] = "Common Gateway Interface";
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
// End -->
答案 0 :(得分:0)
那是因为:
answers[0] = "Apple", "Test" ;
^ just a string literal
answers[0]
只有Apple
作为其值。
你应该这样做:
answers[0] = "Test";
我想。
答案 1 :(得分:0)
如果我理解你在寻找什么,有几种方法你可以做到这一点。一种方法是为每个测验存储一个答案数组,并在封装数组中枚举每个测验:
var quizKey = [
["Apple", "Dynamic HTML", "Netscape", "Common Gateway Interface"]
["Quiz2Answer1", "Quiz2Answer2", "Quiz2Answer3", "Quiz2Answer4"]
["Quiz3Answer1", "Quiz3Answer2", "Quiz3Answer3", "Quiz3Answer4"]
];
现在,您的第一个测验的答案数组将在quizKey[0]
,您的第二个测验的答案数组将在quizKey[1]
,而您的第三个测验的答案数组将在quizKey[2]
中}。您可以轻松地动态添加更多答案:
var newSetOfAnswers = ["foo", "bar", "baz", "gaz"];
quizKey.push(newSetOfAnswers);
请务必跟上枚举。
在我看来,一个更好的方法是命名测验,这样你就不会有太多麻烦试图跟踪测验的数量,你可以将你的密钥存储在地图中:
var quizKey = {
"quiz" : ["Apple", "Dynamic HTML", "Netscape", "Common Gateway Interface"]
"text" : ["Quiz2Answer1", "Quiz2Answer2", "Quiz2Answer3", "Quiz2Answer4"]
"exam" : ["Quiz3Answer1", "Quiz3Answer2", "Quiz3Answer3", "Quiz3Answer4"]
};
动态添加新的答案集非常容易,您还有机会为其命名:
var newSetOfAnswers = ["foo", "bar", "baz", "gaz"];
quizKey["excellentTest"] = newSetOfAnswers;