猿问

如何创建在不同页面上有不同问题的测验?

我想在每个页面的末尾创建一个小测验。我有一个用JavaScript编写的测验,但我希望不同的问题出现在不同的页面中。简而言之,如果我在其他页面上,我希望const myQuestions更改。我怎样才能做到这一点?


我已经尝试过if语句,但无法实现所需的功能。任何帮助将不胜感激!


这是测验的JS代码


(function() {


  const myQuestions = [

    {

      question: "question 1?",

      answers: {

        a: "one",

        b: "two",

        c: "three"

      },

      correctAnswer: "c"

    },

    {

      question: "question 2?",

      answers: {

        a: "one",

        b: "two",

        c: "three"

      },

      correctAnswer: "c"

    },

    {

      question: "question 3?",

      answers: {

        a: "one",

        b: "two",

        c: "three"

        d: "four"

      },

      correctAnswer: "d"

    }

  ];




  function buildQuiz() {

    // we'll need a place to store the HTML output

    const output = [];


    // for each question...

    myQuestions.forEach((currentQuestion, questionNumber) => {

      // we'll want to store the list of answer choices

      const answers = [];


      // and for each available answer...

      for (letter in currentQuestion.answers) {

        // ...add an HTML radio button

        answers.push(

          `<label>

             <input type="radio" name="question${questionNumber}" value="${letter}">

              ${letter} :

              ${currentQuestion.answers[letter]}

           </label>`

        );

      }


      // add this question and its answers to the output

      output.push(

        `<div class="slide">

           <div class="question"> ${currentQuestion.question} </div>

           <div class="answers"> ${answers.join("")} </div>

         </div>`

      );

    });


    // finally combine our output list into one string of HTML and put it on the page

    quizContainer.innerHTML = output.join("");

  }


  function showResults() {

    // gather answer containers from our quiz

    const answerContainers = quizContainer.querySelectorAll(".answers");


    // keep track of user's answers

    let numCorrect = 0;



湖上湖
浏览 128回答 1
1回答

慕少森

里程可能会有所不同,具体取决于您要做什么。仅使用javascript,您就可以windows.location.pathname在每次调用函数时传递给您的函数,并选择与所需路径相关的问题的合适对象。if (windows.location.pathname).includes('page1') {&nbsp; let currentQuestion = myQuestions[0]}&nbsp;//...rest of the logic
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答