制作测验应用程序,坚持功能

时间:2014-01-23 11:04:55

标签: javascript

我正在制作一个简单的测验应用。但是我一直在订购这些功能。

这是代码

// questions set
var qtnsSet = [
  // format: [question, [comma, separated, options], index of correct ans. eg. 1]

  ["What is the full form of IP?", ["Internet Provider", "Internet Port", "Internet Protocol"], 2],
  ["Who is the founder of Microsoft?", ["Bill Gates", "Steve Jobs", "Steve Wozniak"], 0],
  ["Full name of IBM?", ["Internet Business Machine", "International Business Machine", "Indian Business Machine"], 1]
]


// init vars
var qtnNo = 0,
  score = 0;

// define elements
var qtnContainer = $("qtn-container"),
  optnsContainer = $("optns-container"),
  submitBtn = $("submit-btn");

function $(id) { // Shortcut for document.getElementById
  return document.getElementById(id);
}

function askQtn() { // ask question
  var optns = qtnsSet[qtnNo][1], // options array
    optnsHtml = "";
  for (var optnNo = 0; optnNo < optns.length; optnNo++) {
    optnsHtml += createOptnHtml(optnNo, optns[optnNo]);
  }
  qtnContainer.textContent = qtnsSet[qtnNo][0]; // question
  optnsContainer.innerHTML = optnsHtml; // options
}

function createOptnHtml(optnNo, optn) { // create html elements for options
  // eg. <li><input type='radio' name='optn' value='Option' id='optn-0'>
  // <label for='optn-0'>Option</label></li>
  return "<li><h3><input type='radio' name='optn' value='" + optn + "' id='optn-" + optnNo + "'>" +
    " <label for='optn-" + optnNo + "'>" + optn + "</label></h3></li>";
}

function getGivenAns() { // get the answer given by user
  var optns = document.getElementsByName("optn");
  for (var optnNo = 0; optnNo < optns.length; optnNo++) {
    if (optns[optnNo].checked) {
      return optnNo; // index of the chosen answer
    }
  }
}

function checkAns() { // check if user's right or not
  if (getGivenAns() == qtnsSet[qtnNo][2]) {
    score += 6; // 6 points for right answer
  }
}

function submitAns() {
  if (qtnNo <= qtnsSet.length) {
    if (getGivenAns()) {
      checkAns();
      qtnNo++;
      askQtn();
    } else {
      alert("Please choose an answer.");
    };
  } else {
    alert("Score: " + score);
  };
}

window.addEventListener("load", askQtn, false);
submitBtn.addEventListener("click", submitAns, false);

我无法配置submitAns()功能,以便每件事都能正常工作。 如何在submitAns()

中订购功能

1 个答案:

答案 0 :(得分:0)

getGivenAns()

返回选项的索引,如果选择了第一个选项,则该索引可以为0,在此处评估为false:

if (getGivenAns()) {

所以如果选中了一个选项,则返回true。

另外

if (qtnNo <= qtnsSet.length) {

在最后一个问题之后它应该是真的

if (qtnNo < qtnsSet.length) {