用jquery和javascript做一个测验

Making a quiz with jquery and javascript

本文关键字:一个 jquery javascript      更新时间:2023-09-26

我正在努力用javascript和jquery做一个测验,但我完全不知道如何继续。目前,我只创建了一个 JSON 来保存问题。

到目前为止的Javascript文档:

    // JavaScript Document
(function(){
    window.onload = init;
    function init(){
    }
    var points = 0;
    var numberofquestions= 0;
    var correct= 0;
    var quiz= {question: [
        {Question: "Question 1?", 
            answers: [
                {answer: "Answer 1", correct_answer: 0},
                {answer: "Answer 2", correct_answer: 1},
                {answer: "Answer 3", correct_answer: 0}
        ]}
    ]};
})();

.HTML

    <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Quiz</title>
<script src="../javascript/quizJS.js"></script>
<link rel="stylesheet" type="text/css" href="../css/stil.css">
</head>
<body>
    <div id="wrapper">
        <header id="header">
            <h1>Quiz</h1>
        </header>
        <div id="container">
            <h2 id="Title"></h2>
            <ul class="answerswer">
            </ul>
            <section id="navigation">
                <button ID="btnPrev">Prev</button>
                <button ID="btnNext">Next</button>
            </section>
        </div>
        <footer id="footer">
        </footer>
    </div>
</body>
</html>

我不要求任何人这样做,但我需要帮助才能取得任何进展。我尝试使用谷歌找到类似的东西,但它看起来很复杂,我无法弄清楚模式。谢谢

我会给你一些想法:

  • 您持有问题的结构是正确的,并且您的初始变量选择正确。这是一个很好的开始。我错过了一个您将设置为 0 的变量"current_question"。

  • 然后我们有 HTML 部分。这似乎也是一个描绘问题的适当结构。

现在,缺少的是第三部分:逻辑。您需要编写一个程序:

  • 1)在HTML中绘制一个问题
  • 2)当用户单击答案时,查看测验数组,当前问题,并检查它是否正确
  • 3) 如果正确,您将向点变量添加一些点。
  • 4)您将执行current_question=current_question + 1并返回步骤1)

这可以补充您的程序

 var current_question_number=0;
 var currentQuestion=null; // we will store the current question here for easy access
 function start_quiz() {
    current_question_number=0;
    correct=0;
    points=0;
    paint_question();       
 }

 // you will call this to paint the current question current_question_number
 function paint_question() {
     currentQuestion=quiz.question[current_question_number];
      // paint the title
      // paint inside a HTML by id: Standard javascript way
      document.getElementById("title").innerText=currentQuestion.Question;
      // or use jquery: $("#title").text(currentQuestion.Question);
      // paint the answers
      var answers=currentQuestion.answers;
      for (var i=0; i<answers.length; i++) {
             var answer=answers[i]; // current answer
             // now you have to add <li>answer</li> to the <ul>
             // this is your homework!
      }
 }
 // you will call this when the user clicks on one answer, with the answer number
 function receive_answer(chosen) {
         if (currentQuestion.answers[chosen].correct_answer==1) {
                 // add the points
         }
         current_question++;
         paint_question();
 }