为测验添加多个答案

时间:2014-04-22 12:43:30

标签: javascript

我需要添加多个问卷来使用相同的代码。我怎么能这样做?

// Insert answers to questions
answers[0] = ["Apple", "Test"] ;
answers[1] = "Dynamic HTML";
answers[2] = "Netscape";
answers[3] = "Common Gateway Interface";

正如你所看到的,我只是尝试将我的其他答案添加到代码中以进行不同的测验,但它无法识别。这样做的最佳方式是什么? (是否有"或"命令或类似的东西?

以下是我的全部代码:

// 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", "Test";
answers[2] = "Netscape",  "Test";
answers[3] = "Common Gateway Interface", "Test";

// 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 -->

2 个答案:

答案 0 :(得分:0)

您可以使用javascript Object literal表示法

var answers = {
    0: ["Apple", "Test"],
    1: "Dynamic HTML",
    2: "Netscape",
    3: "Common Gateway Interface"
};

您可以使用答案[0],答案[1],...

来访问您的答案

你是说这个吗?

答案 1 :(得分:0)

您需要一个多维数组概念,以便为答案提供更灵活的选项,如下所示:

var answers = [
    ['Apple','Test'],
    ['Dynamic HTML','DHTML']
    ['Netscape',''], //you can live this blank
    ['Common Gateway Interface','CGI']
];

//如何访问答案,就像你想要更多值来比较

if((answers [0][0] == 'Appel')||(answers[0][1] == 'Test')) {
   alert('Correct Answer');
}

选项二: 有关详情,请参阅此question and answer并告知我们。

Tested Here See result