学习动态测验Javascript并有疑问

时间:2014-05-10 19:09:15

标签: javascript html dynamic

我正在关注javascriptissexy并学习如何进行动态测验。我找到了某人自己的测验版本并查看了源代码,以了解他们是如何解决问题的;在我采取了一个裂缝之后。我理解html / css和一些javascript代码,但需要回答一些问题。我希望有人可以回答一些关于他们的源代码的问题。我的问题在底部。

以下是完整应用http://codepen.io/gcarino/pen/LDgtn/

的链接

这是完整的JavaScript代码:

(function() {
  var questions = [{
    question: "What is 2*5?",
    choices: [2, 5, 10, 15, 20],
    correctAnswer: 2
  }, {
    question: "What is 3*6?",
    choices: [3, 6, 9, 12, 18],
    correctAnswer: 4
  }, {
    question: "What is 8*9?",
    choices: [72, 99, 108, 134, 156],
    correctAnswer: 0
  }, {
    question: "What is 1*7?",
    choices: [4, 5, 6, 7, 8],
    correctAnswer: 3
  }, {
    question: "What is 8*8?",
    choices: [20, 30, 40, 50, 64],
    correctAnswer: 4
  }];

  var questionCounter = 0; //Tracks question number
  var selections = []; //Array containing user choices
  var quiz = $('#quiz'); //Quiz div object

  // Display initial question
  displayNext();

  // Click handler for the 'next' button
  $('#next').on('click', function (e) {
    e.preventDefault();

    // Suspend click listener during fade animation
    if(quiz.is(':animated')) {        
      return false;
    }
    choose();

    // If no user selection, progress is stopped
    if (isNaN(selections[questionCounter])) {
      alert('Please make a selection!');
    } else {
      questionCounter++;
      displayNext();
    }
  });

  // Click handler for the 'prev' button
  $('#prev').on('click', function (e) {
    e.preventDefault();

    if(quiz.is(':animated')) {
      return false;
    }
    choose();
    questionCounter--;
    displayNext();
  });

  // Click handler for the 'Start Over' button
  $('#start').on('click', function (e) {
    e.preventDefault();

    if(quiz.is(':animated')) {
      return false;
    }
    questionCounter = 0;
    selections = [];
    displayNext();
    $('#start').hide();
  });

  // Animates buttons on hover
  $('.button').on('mouseenter', function () {
    $(this).addClass('active');
  });
  $('.button').on('mouseleave', function () {
    $(this).removeClass('active');
  });

  // Creates and returns the div that contains the questions and 
  // the answer selections
  function createQuestionElement(index) {
    var qElement = $('<div>', {
      id: 'question'
    });

    var header = $('<h2>Question ' + (index + 1) + ':</h2>');
    qElement.append(header);

    var question = $('<p>').append(questions[index].question);
    qElement.append(question);

    var radioButtons = createRadios(index);
    qElement.append(radioButtons);

    return qElement;
  }

  // Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('<ul>');
    var item;
    var input = '';
    for (var i = 0; i < questions[index].choices.length; i++) {
      item = $('<li>');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += questions[index].choices[i];
      item.append(input);
      radioList.append(item);
    }
    return radioList;
  }

  // Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }

  // Displays next requested element
  function displayNext() {
    quiz.fadeOut(function() {
      $('#question').remove();

      if(questionCounter < questions.length){
        var nextQuestion = createQuestionElement(questionCounter);
        quiz.append(nextQuestion).fadeIn();
        if (!(isNaN(selections[questionCounter]))) {
          $('input[value='+selections[questionCounter]+']').prop('checked', true);
        }

        // Controls display of 'prev' button
        if(questionCounter === 1){
          $('#prev').show();
        } else if(questionCounter === 0){

          $('#prev').hide();
          $('#next').show();
        }
      }else {
        var scoreElem = displayScore();
        quiz.append(scoreElem).fadeIn();
        $('#next').hide();
        $('#prev').hide();
        $('#start').show();
      }
    });
  }

  // Computes score and returns a paragraph element to be displayed
  function displayScore() {
    var score = $('<p>',{id: 'question'});

    var numCorrect = 0;
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
      }
    }

    score.append('You got ' + numCorrect + ' questions out of ' +
                 questions.length + ' right!!!');
    return score;
  }
})();

我的问题:

1)关于这段代码

 // Click handler for the 'next' button
  $('#next').on('click', function (e) {
    e.preventDefault();

    // Suspend click listener during fade animation
    if(quiz.is(':animated')) {        
      return false;
    }

1.a函数参数中的e或(e)是什么以及e.preventDefault()的作用是什么?

1.b如何在淡入淡出动画期间返回false暂停点击侦听器?

2)关于这段代码:

function createQuestionElement(index) {
    var qElement = $('<div>', {
      id: 'question'
    });

    var header = $('<h2>Question ' + (index + 1) + ':</h2>');
    qElement.append(header);

    var question = $('<p>').append(questions[index].question);
    qElement.append(question);

    var radioButtons = createRadios(index);
    qElement.append(radioButtons);

    return qElement;
  }

1.a函数参数中的(索引)是什么?我看到在函数体中使用但不知道它在html或js代码中引用了什么。

我认为现在就是这样。谢谢你的帮助。

3 个答案:

答案 0 :(得分:0)

1.a)eeventObjecte.preventDefault()方法停止发生元素的默认操作,在本例中为点击。

1.b)点击事件中的return false也会停止点击执行默认操作,这可能是打开网址

2)index是从另一个代码块发送的参数,在这种情况下,如果你检查整个代码,它会说:var nextQuestion = createQuestionElement(questionCounter);所以在这种情况下索引是要显示的下一个问题的数量

答案 1 :(得分:0)

1a - e是引用事件参数的变量。 e.preventDefault()会阻止默认事件操作完成 - 在这种情况下,它会阻止click操作启动。

1b - 从jQuery事件处理程序返回false可防止事件触发并阻止事件冒泡。 (有关详细信息,请参阅this SO post

2如果您查看displayNext功能,questionCounter似乎正在跟踪问题总数。因此,当调用createQuestionElement时,会将此questionCounter作为参数传递(这是要创建的下一个问题的编号)

答案 2 :(得分:0)

1.a)使用e只是事件的简称。您可以传递任何您想要的变量名称。 e.preventDefault();将停止事件的默认操作。在这种情况下,点击它。

1.b)通过返回false,您将阻止代码的剩余部分被触发。一旦浏览器遇到返回false,它就不会执行它下面的代码的剩余部分。

2)索引是函数的参数。您将在调用函数时传递参数。

在这种情况下:

var radioButtons = createRadios(index);

通过传递问题索引来调用该函数。

如您所见,

var questions = [{
    question: "What is 2*5?",
    choices: [2, 5, 10, 15, 20],
    correctAnswer: 2
  },  {
    question: "What is 3*6?",
    choices: [3, 6, 9, 12, 18],
    correctAnswer: 4
  }]

问题是一个数组,因此您将索引传递给createRadio方法,以便根据提供的选项在那里引用相同的问题来构建单选按钮。