【问题标题】:I want to collect all the user answers ( checked radios and checkboxes) and see if the user has selected the correct answer. If so, score++我想收集所有用户的答案(选中的单选和复选框),看看用户是否选择了正确的答案。如果是这样,得分++
【发布时间】:2021-12-19 01:29:21
【问题描述】:

代码没有按照我的意愿执行。我确定缺少某些东西,但不知道是什么。当我点击“检查分数”按钮时,我希望它显示分数,但现在它只显示“你得分:0/10。我的 displayScore() 函数不起作用。 谁能告诉我我在这里缺少什么?请注意,使用 checkboxex 的问题有两个可能的正确答案。

(function () {
  function renderQuiz() {

    const quizContainer = document.querySelector("#quizContainer");
    let quizStr = '';

    // Loops over the object properties (obj) and also takes an index parameter
    quiz.forEach((obj, questionIndex) => {
      // Empty string to keep the li element containing the label and input
      let answerStr = '';
      //Loops over the options object inside of the array quiz
      for (const option in obj.options) {
        /* If it has an object that has an array as a value it renders the inputs as checkboxes */
        if (Array.isArray(obj.correct) === true) {
          answerStr += `
                  <li>
                  <label>
                  <input 
                  value=""
                  type="checkbox"
                  name="question-${questionIndex}"
                  data-correct="${obj.correct}"
                  >
                  ${obj.options[option]}
                  </label>
                  <li> `;
          /* Else it renders the inputs as radiobuttons */
        } else {
          answerStr += `
                  <li>
                  <label>
                  <input 
                  type="radio"
                  name="question-${questionIndex}"
                  data-correct="${obj.correct}"
                  >
                  ${obj.options[option]}
                  </label>
                  <li> `;
        }
      }
      quizStr += `
          <form>
              <h3>${obj.question}</h3>
              <ul>
              ${answerStr}
              </ul>
          </form> `;
    })

    quizContainer.innerHTML = quizStr;
  }

  const resultsContainer = document.querySelector("#results");
  // Adds held score to total and displays a text with the score
  function displayScore() {

    const answerContainer = [];

    quiz.forEach((obj, questionIndex) => {

      let userAnswer = `input[name="question-${questionIndex}]:checked`;
      let answers = [];

      if (userAnswer >= 2) {
        userAnswer.forEach(e => {
          let selected = e.target.userAnswer;
          answers.push(selected);
        })
      } else {
        answers = userAnswer[0];
      }
      answerContainer.push(answers);
    });

    let score = 0;

    for (let i = 0; i < quiz.length; i++) {
      let correctAnswer = quiz[i].correct;
      let userChoice = answerContainer[0];

      if (Array.isArray(correctAnswer)) {
        if (JSON.stringify(correctAnswer) === JSON.stringify(userChoice)) {
          score++;
        }
      } else if (correctAnswer === userChoice) {
        score++;
      }
    }

    resultsContainer.innerHTML = `<p>You scored : ${score} / ${quiz.length}</p>`;
  }

  // Objects with question sections within an array
  let quiz = [
    {
      question: "I vilket land produceras det mest kaffe?",
      options: {
        a: "Kolombia",
        b: "Brasilien",
        c: "Indonesien",
        d: "Vietnam"
      },
      correct: "b"
    },
    {
      question: "I vilket land konsumeras det mest kaffe?",
      options: {
        a: "Italien",
        b: "Belgien",
        c: "Finland",
        d: "Kanada"
      },
      correct: "c"
    },
    {
      question: "Ordet kaffe betyder vin på det språket det härstammar ifrån. Vilket språk är det?",
      options: {
        a: "Arabiska",
        b: "Ryska",
        c: "Turkiska",
        d: "Grekiska"
      },
      correct: "a"
    },
    {
      question: "Hur många kalorier finns i en kopp kaffe?",
      options: {
        a: "1",
        b: "5",
        c: "14",
        d: "7"
      },
      correct: "a"
    },
    {
      question: "Vem upptäckte kaffet?",
      options: {
        a: "En bonde",
        b: "En fåraherde",
        c: "En munk",
        d: "En jägare"
      },
      correct: "b"
    },
    {
      question: "På vilket djurs avföring är världens dyraste kaffe gjord på?",
      options: {
        a: "Mus",
        b: "Fågel",
        c: "Apa",
        d: "Katt"
      },
      correct: "d"
    },
    {
      question: "När kom kaffet till Sverige?",
      options: {
        a: "1700-talet",
        b: "1800-talet",
        c: "1400-talet",
        d: "1600-talet"
      },
      correct: "d"
    },
    {
      question: "Vilka två av dessa alternativ är typer av kaffe?",
      options: {
        a: "Arabica",
        b: "Mocca",
        c: "Robusta",
        d: "Java"
      },
      correct: ["a", "c"]
    },
    {
      question: "Välj de enda två delstaterna i U.S.A som odlar kaffebönor?",
      options: {
        a: "Georgia",
        b: "Kalifornien",
        c: "Hawaii",
        d: "Florida"
      },
      correct: ["b", "c"]
    },
    {
      question: "Hur förvaras kaffe som bäst? Välj två sätt.",
      options: {
        a: "Svalt",
        b: "I kylskåp",
        c: "Öppet",
        d: "Mörkt"
      },
      correct: ["a", "d"]
    }
  ];

  renderQuiz();

  let checkButton = document.querySelector("#check");
  checkButton.addEventListener("click", displayScore)
})();

【问题讨论】:

  • 仅使用脚本很难处理您的代码。请调整您的问题以包含 HTML、CSS 和 JavaScript,以便我们可以在它运行时与之交互。

标签: javascript arrays function javascript-objects addeventlistener


【解决方案1】:

以下是 HTML 和 CSS: (忽略id为toggleBtns的div及其内容)

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css">
   <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Poppins&display=swap" rel="stylesheet">
   <link rel="stylesheet" href="style.css">
   <title>Kaffe Quiz</title>
</head>
<body>
   <main>
       <div id="toggleBtns">
           <button id="black" class="btn active">Black</button>
           <button id="milk" class="btn">Milk</button>  
       </div>
       <section id="quizSection">
           <h1><i class="fas fa-mug-hot"></i>Kaffe Quiz<i class="far fa-lightbulb"></i></h1>
       <div id="quizContainer"></div>
       <div id="buttonContainer">
               <button id="retry">TRY AGAIN</button>
               <button id="check">CHECK SCORE</button>
           </div>
           <div id="results"></div>
       </section>
</main>
   <script src="script.js"></script>
</body>
</html>


* {
   box-sizing: border-box;
}

body {
   font-family: 'Poppins', sans-serif; 
   color: white;
}

main::before {
   content: '';
   background-image:linear-gradient(
       115deg,
       rgba(236, 225, 203, 0.5),
       rgba(228, 203, 163, 0.5)
     ), url(https://images.pexels.com/photos/1695052/pexels-photo-1695052.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500)
   ;
   position: fixed;
   top: 0;
   left: 0;
   height: 100%;
   width: 100%;
   z-index: -1;
 background-position: center;
 filter: grayscale(45%); 
}

#toggleBtns {
   display: flex;
   justify-content: center;
   align-self: center;
   text-align: center;
   margin-top: 70px;
} 

#toggleBtns button {
   width: 60px;
   font-weight: bolder;
   height: 40px;
   cursor: pointer;
}

.active, .btn button:hover {
   border: 2px solid turquoise;
}

#black {
   background: rgba(37, 37, 36);
   color: white;
}

h1{
   text-align: center;
   letter-spacing: 3px;
   font-size: 30px;
}

i {
   margin: 20px;
}

#quizSection {
   max-width: 800px;
   min-width: 450px;
   background: rgba(37, 37, 36, 0.9);
   border-radius: 20px;
   overflow: hidden;
   margin: 50px auto;
}

h3 {
   margin: 50px auto;
   border-bottom: 1px solid rgba(116, 116, 110, 0.9);
   max-width: 700px;
   padding: 30px;
   letter-spacing: 2px;
   font-weight: bolder;
}

p {
   font-size: 30px;
   margin: 100px auto;
   text-align: center;
}

input {
   margin-left: 50px;
   margin-right: 30px;
}

label {
   margin-left: 20px;
   font-size: 18px;
}

ul {
   list-style: none;
}

li {
   line-height: 2;
}

#buttonContainer{
   display: flex;
   justify-content: center;
   margin: 100px auto;
   text-align: center;
}

#buttonContainer button{
   padding: 10px 20px;
   width: 100px;
   height: 50px;
   background: turquoise;
   font-weight: bold;
   border: none;
   border-radius: 10px;
   margin: 15px;
   cursor: pointer;
   color: rgba(37, 37, 36);
}

#buttonContainer button:hover {
   background: rgb(17, 199, 84);
   transition: ease-in-out 0.5s;
}


【讨论】:

    猜你喜欢
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2018-01-20
    • 2021-12-18
    • 2015-08-09
    • 2019-01-12
    相关资源
    最近更新 更多