Как добавить балл в конце моей викторины. Пример: «10/10» или «0/10». Как вы можете видеть в моем коде, я создал статическую часть с помощью HTML и CSS и динамическую часть с помощью Javascript, я часами искал решение, но ничего не приходило мне в голову. Чего я хочу: закончите, отобразив счет с небольшим сообщением «Поздравляю» или «Неудача».

Надеюсь, вы поможете, так как я еще новичок, спасибо!

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let RandomQuestions, currentQuestion

startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
  currentQuestion++
  setNextQuestion()
})

function startGame() {
  startButton.classList.add('hide')
  RandomQuestions = questions.sort(() => Math.random() - .5)
  currentQuestion = 0
  questionContainerElement.classList.remove('hide')
  setNextQuestion()
}

function setNextQuestion() {
  resetState()
  showQuestion(RandomQuestions[currentQuestion])
}

function showQuestion(question) {
  questionElement.innerText = question.question
  question.answers.forEach(answer => {
    const button = document.createElement('button')
    button.innerText = answer.text
    button.classList.add('btn')
    if (answer.correct) {
      button.dataset.correct = answer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
  })
}

function resetState() {
  clearStatusClass(document.body)
  nextButton.classList.add('hide')
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (RandomQuestions.length > currentQuestion + 1) {
    nextButton.classList.remove('hide')
  } else {
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

function setStatusClass(element, correct) {
  clearStatusClass(element)
  if (correct) {
    element.classList.add('correct')
  } else {
    element.classList.add('wrong')
  }
}

function clearStatusClass(element) {
  element.classList.remove('correct')
  element.classList.remove('wrong')
}

const questions = [
  {
    question: 'What is the rarest blood type?',
    answers: [
      { text: 'AB-Negative', correct: true },
      { text: 'O', correct: false }
    ]
  },
  {
    question: 'What sport does Cristiano Ronaldo play?',
    answers: [
      { text: 'Football', correct: true },
      { text: 'Tennis', correct: false },
      { text: 'Skateboarding', correct: false },
      { text: 'Racing', correct: false }
    ]
  },
  {
    question: "“Keep Calm and Carry On” is the slogan of which nation?",
    answers: [
      { text: 'Britain', correct: true },
      { text: 'Switzerland', correct: false },
      { text: 'Japan', correct: false },
      { text: 'Germany', correct: false }
    ]
  },
  {
    question: '"Fe" is the chemical symbol for which element?',
    answers: [
      { text: 'Iron', correct: true },
      { text: 'Oxygene', correct: false },
      { text: 'Potassium', correct: false },
      { text: 'Gold', correct: false }
    ]
  }
]
*, *::before, *::after {
    box-sizing: border-box;
  }
  
  :root {
    --color-neutral: 200;
    --color-wrong: 0;
    --color-correct: 145;
  }
  
  body {
    --color: var(--color-neutral);
    padding: 0;
    margin: 0;
    display: flex;
    width: 100vw;
    height: 100vh;
    justify-content: center;
    align-items: center;
    background-color: hsl(var(--color), 100%, 20%);
  }
  
  
  .container {
    width: 800px;
    max-width: 80%;
    background-color: white;
    border-radius: 5px;
    padding: 10px;
    box-shadow: 0 0 10px 2px;
  }
  
  .btn-grid {
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 10px;
    margin: 20px 0;
  }
  
  .btn {
    --color: var(--color-neutral);
    border: 1px solid hsl(var(--color), 100%, 30%);
    background-color: hsl(var(--color), 100%, 50%);
    border-radius: 5px;
    padding: 5px 10px;
    color: white;
    outline: none;
  }
  
  .btn:hover {
    border-color: black;
  }
  
  .btn.correct {
    --color: var(--color-correct);
    color: black;
  }
  
  .btn.wrong {
    --color: var(--color-wrong);
  }
  
  .start-btn, .next-btn {
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
  }
  
  .controls {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .hide {
    display: none;
  }
  
  
  
  
  /* Background Styles Only */
  
  @import url('https://fonts.googleapis.com/css?family=Raleway');
  
  
  html {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #DFDFDF;
  }

  
  
  
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <script defer src="script.js"></script>
</head>
<body>
    <div class="container">
        <div id="question-container" class="hide">
          <div id="question">Question</div>
          <div id="answer-buttons" class="btn-grid">
            <button class="btn">Answer 1</button>
            <button class="btn">Answer 2</button>
            <button class="btn">Answer 3</button>
            <button class="btn">Answer 4</button>
          </div>
        </div>
        <div class="controls">
          <button id="start-btn" class="start-btn btn">Start</button>
          <button id="next-btn" class="next-btn btn hide">Next</button>
        </div>
      </div>

</body>
</html>
2
Koussay Hamdi 22 Фев 2021 в 01:54

1 ответ

Лучший ответ

Просто создайте переменную, содержащую количество правильных ответов, сделайте ее равной 0:

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let RandomQuestions, currentQuestion
var correctAnswers = 0

Измените функцию selectAnswer (e), как показано ниже:

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  if (correct) {
     correctAnswers++
  }
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (RandomQuestions.length > currentQuestion + 1) {
    nextButton.classList.remove('hide')
  } else {
    display(correctAnswers.toString() + "/" + RandomQuestions.length.toString())
    correctAnswers = 0
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

Конечно, замените display () чем-нибудь вроде element.innerText = correctAnswers.toString() + "/" + RandomQuestions.length.toString()

2
mr noob 22 Фев 2021 в 13:24