• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Podwójnie kliknięcie w quizie

Aruba Cloud - Virtual Private Server VPS
+1 głos
276 wizyt
pytanie zadane 26 listopada 2021 w JavaScript przez sam123 Nowicjusz (130 p.)
edycja 26 listopada 2021 przez sam123

Witam, jestem nowy w js i stworzyłem sobie quiz, który ma taki kod: 
Gdy klikam poprawną odpowiedź w 2 pytaniu wartość i dziwnie się mnoży razy dwa. Nie jestem w stanie powiedzieć czemu tak się dzieje. Czy jest w stanie ktoś mi pomóc i powiedzieć co jest nie tak ? Jeśli ktoś ma inny sposób na zrobienie takiego quizy to jestem otwarty na propozycje. Proszę

const quiz = document.getElementById('milionaresQuiz');
const allLooserButtons = document.getElementById('loserButtons');
const questions = [{
        question: "Najwyższy budynek świata Burj Khalifa zwieńczony jest tym samym elementem architektonicznym, to:",
        choices: ["Krzywa Wieża w Pizie", "PKiN", "Opera w Sydney", "Statua Wolności"],
        answer: 1
    },

    {
        question: "Który król założył obok Krakowa miasta Kazimierz i Kleparz?",
        choices: ["Kazimierz III Wielki", "Kazimierz II Sprawiedliwy", "Kazimierz I Odnowiciel", "Władysław Łokietek"],
        answer: 0
    },

    {
        question: "pytanie3",
        choices: ["odp1", "odp2", "odp3", "odp4"],
        answer: 2
    },

    {
        question: "ostatnie pytanie",
        choices: ["odp1", "odp2", "odp3", "odpowiedz4"],
        answer: 3
    },

];


function goodAnswer(myElement) { 
        myElement.style.backgroundColor = "";
        i++;
}

function wrongAnswer() {
    quiz.innerHTML = " ";

    let h3 = document.createElement('h3');
    h3.innerHTML = "Przegrałeś ";
    quiz.insertAdjacentElement("beforeend", h3);

    let allLooserButtons = document.createElement('div');
    allLooserButtons.id = "loserButtons";
    quiz.insertAdjacentElement("beforeend", allLooserButtons)


    let checkPoints = document.createElement('button');
    checkPoints.className = "loserButtons";
    checkPoints.innerHTML = "Pokaż wyniki";
    allLooserButtons.insertAdjacentElement("beforeend", checkPoints)

    let startNewGame = document.createElement('button');
    startNewGame.className = "loserButtons";
    startNewGame.innerHTML = "Nowa gra";
    allLooserButtons.insertAdjacentElement("beforeend", startNewGame)

    checkPoints.addEventListener('click', function () {
        let points = document.createElement('p');
        points.id = "points";
        quiz.insertAdjacentElement("beforeend", points);
        document.getElementById('points').innerHTML = "Liczba zdobytych punktów - " + i;

    })


}


var i = 0;

function showQuestion(q) {

    const title = document.getElementById('question');

    title.textContent = questions[i].question;

    let userChoices = document.querySelectorAll('.userChoices');

    userChoices.forEach(function (element, index) {
        element.textContent = index + 1 + ". " + q[i].choices[index];

        element.addEventListener('click', function () {
            if (questions[i].answer == index) {
                console.log("index =" +index)
                element.style.backgroundColor = "lightgreen";
                setTimeout(() => {
                    goodAnswer(element);
                    showQuestion(questions);
                }, 500)


            } else {
                element.style.backgroundColor = "red";

                setTimeout(() => {
                    wrongAnswer()
                }, 1000)


            }
        })
    });
}

showQuestion(questions);

 

html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>

<body>
    <div class="container">
        <div class="milionerzy" id="milionaresQuiz">
            <h1 style="text-align: center;" id="question">Kliknij przycisk start</h1>
            <br>
            <div id="quiz" class="quiz">
                <h2 class="userChoices"></h2>
                <h2 class="userChoices"></h2>
                <h2 class="userChoices"></h2>
                <h2 class="userChoices"></h2>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>

</html>


css:

body {
    background-color: #729ea1;
}

.container {
    border: none;
    width: 95%;
    min-height: 100vh;
    margin: auto;
    display: flex;
}

.milionerzy {
    border-radius: 15px;
    width: 800px;
    height: 680px;
    margin: auto;
    background-color: white;
    box-shadow: 8px 8px 24px 2px;
}

.milionerzy h1 {
    border-bottom: 3px solid #182525;
    width: 90%;
    margin: auto;
    margin-top: 35px;
    padding-bottom: 20px;
}

.btns {
    margin-top: 25px;
}

h3 {
    font-size: 4rem;
    text-align: center;
    margin-top: 100px;
    font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
}

.quiz h2 {
    border: 2px solid #416062;
    background-color: #ceddde;
    height: 60px;
    width: 90%;
    margin-left: 5%;
    margin-bottom: 40px;
    font-size: 1.5rem;
}

.quiz h2:hover {
    border: 2px solid #182525;
    background-color: #77a6a6;
}

.loserButtons {
    margin-left: 5px;
    font-size: 2rem;
}

#loserButtons {
    display: flex;
    justify-content: center;
}

p {
    font-size: 1.5rem;
    text-align: center;
    margin-top: 50px;
}

 

2 odpowiedzi

0 głosów
odpowiedź 26 listopada 2021 przez Wiciorny Ekspert (280,450 p.)

var i = 0;

to i tak zostanie wywindowane "hoisting" na górę,  

i++;

masz post inkrementacje zmiennej globalnej więc ona będzie zawsze zwiększona po operacji obsługi pytania, która wartość się mnoży, trudno jest przedbugować kod bez całości . Potencjalnie widzę albo w tym problem, albo to że wywołujesz funkcje w setTimeout jako callback. 
Wrzuć również html'a

komentarz 26 listopada 2021 przez sam123 Nowicjusz (130 p.)
Dodałem
komentarz 26 listopada 2021 przez Wiciorny Ekspert (280,450 p.)

problem jest w tym, że robisz 

 userChoices.forEach(function (element, index)

dla każdego wyboru dodajesz odpowiednie akcje, przy samym załadowaniu strony to wywołanie w pętli wykona się 4 razy, tyle ile jest odp. na pytania 

za każdym razem obiekt "element" jest wywoływany przy 3 pytaniu powieli się event listener 3 razy. i tak w kółko 

komentarz 26 listopada 2021 przez sam123 Nowicjusz (130 p.)
edycja 28 listopada 2021 przez sam123
Dzięki za pomoc
0 głosów
odpowiedź 3 grudnia 2021 przez VBService Ekspert (256,600 p.)
edycja 3 grudnia 2021 przez VBService

Ustaw zdarzenie click tylko raz na

<h2 class="userChoices"></h2>
<h2 class="userChoices"></h2>
<h2 class="userChoices"></h2>
<h2 class="userChoices"></h2>

 

np. zaraz po "załadowaniu" strony.

<div class="answers">
  <p data-lp="1">Lorem 1</p>
  <p data-lp="2">Lorem 2</p>
  <p data-lp="3">Lorem 3</p>
  <p data-lp="4">Lorem 4</p>
</div>
.answers p {
  cursor: pointer;
}
let answers; 
window.addEventListener('load', load);
 
function load() {
  answers = document.querySelectorAll('.answers p');
  for (const answer of answers)
    answer.addEventListener('click', checkAnswer);
}
 
function checkAnswer(e) {
  console.log(e.target, parseInt(e.target.dataset.lp), e.target.textContent);
}

 

 

przykład

<div class="container">
  <div class="rows-layout">
    <div class="question">
      <p></p>
    </div>
    <div class="answers">
      <p data-lp="1"></p>
      <p data-lp="2"></p>
      <p data-lp="3"></p>
      <p data-lp="4"></p>
    </div>  
    <div class="statistic">
      <div class="good-answers">Prawidłowych odpowiedzi: <span>0</span></div>
      <div class="wrong-answers">Nieprawidłowych odpowiedzi: <span>0</span></div>
    </div>
  </div>
</div>
* {
  box-sizing: border-box;
}
html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100vh;
  background-color: #729ea1;
}
.container {
  border: 0;
  width: 90%;
  height: 95%;
  margin: 1em auto;
  border-radius: 1em;
  box-shadow: 8px 8px 24px 2px;
  background-color: white;
  font: 400 1em/1.1 tahoma;
}
.container .rows-layout  {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 3fr 0.5fr;
  gap: 0px 0px;
  grid-template-areas:
    "question" "answers" "statistic";

  width: 90%;
  height: 100%;
  margin: 1em auto;
}

.rows-layout .question { 
  grid-area: question;
  border-bottom: 0.1em solid black;
}
.rows-layout .answers { 
  grid-area: answers; 
}
.rows-layout .answers p {
  position: relative;
  cursor: pointer;
  border: 2px solid #416062;
  background-color: #ceddde;
  transition: all 0.25s;
  padding: 1em 0.5em 1em 2em;
  border-radius: 0.5em;
}
.rows-layout .answers p:hover {
  border: 2px solid #182525;
  background-color: #77a6a6;
}
.rows-layout .answers p::before {
  position: absolute;
  top: 50%;
  left: 0.5em;
  transform: translateY(-50%);
  content: attr(data-lp);
  font: 400 1.5em monospace;
  color: rgba(0,0,0,0.4);
}
.rows-layout .statistic {
  grid-area: statistic;
  border-top: 0.1em solid black;
}
.rows-layout .statistic div {
  display: inline-block;
  margin: 0.5em 2em 0.5em 0;
  font: 700 1.2em monospace;
}
.rows-layout .statistic div span {
  display: inline-block;
  font: 700 1.4em monospace;
  width: 2em;
}
.rows-layout .statistic .good-answers span {
  color: limegreen;
}
.rows-layout .statistic .wrong-answers span {
  color: orangered;
}
.backlight-good-answer {
  background-color: limegreen !important;
  color: white;
}
.backlight-wrong-answer {
  background-color: red !important;
  color: white;
}
const quiz = [
  { 
    question : 'Pytanie 1',
    answers : [ 
      'Odpowiedź 1.1', 'Odpowiedź 1.2', 
      'Odpowiedź 1.3', 'Odpowiedź 1.4'
    ],
    correct : 1
  },
  { 
    question : 'Pytanie 2',
    answers : [ 
      'Odpowiedź 2.1', 'Odpowiedź 2.2',
      'Odpowiedź 2.3', 'Odpowiedź 2.4'             
    ],
    correct : 2
  },
  { 
    question : 'Pytanie 3',
    answers : [ 
      'Odpowiedź 3.1', 'Odpowiedź 3.2',
      'Odpowiedź 3.3', 'Odpowiedź 3.4'             
    ],
    correct : 3
  },
  { 
    question : 'Pytanie 4',
    answers : [ 
      'Odpowiedź 4.1', 'Odpowiedź 4.2',
      'Odpowiedź 4.3', 'Odpowiedź 4.4'             
    ],
    correct : 4
  }  
];

let qestion, answers, good_answers, wrong_answers,
    question_current_id = 0, next_question;

window.addEventListener('load', load);

function load() {
  qestion = document.querySelector('.question p');
  answers = document.querySelectorAll('.answers p');
   good_answers = document.querySelector('.good-answers span');
  wrong_answers = document.querySelector('.wrong-answers span');

  for (const answer of answers)
    answer.addEventListener('click', checkAnswer);

  selectQuestion();
}

function selectQuestion() {
  question_current_id = Math.floor(Math.random() * quiz.length);
  qestion.textContent = quiz[question_current_id].question;

  for (let i=0; i<answers.length ;i++)
    answers[i].textContent = quiz[question_current_id].answers[i];

  next_question = false;
}

function checkAnswer(e) {
  if (! next_question) {
    let backlight_answer = 'backlight-wrong-answer';
    if (parseInt(e.target.dataset.lp) == quiz[question_current_id].correct) {
      good_answers.textContent = parseInt(good_answers.textContent) + 1;
      backlight_answer = 'backlight-good-answer';
    } else
      wrong_answers.textContent = parseInt(wrong_answers.textContent) + 1;

    next_question = true;
    e.target.classList.add(backlight_answer);
    void e.target.offsetWidth;
    setTimeout(nextQuestion, 2000, e.target, backlight_answer);
  }
}

function nextQuestion(element, css) {
  element.classList.remove(css);
  element = element.closest('.answers').style;
  element.cssText = 'filter: blur(5px);';
  setTimeout(function() { 
    element.cssText = 'filter: none;';
    selectQuestion(); 
  }, 500);  
}

 

Podobne pytania

0 głosów
1 odpowiedź 1,106 wizyt
pytanie zadane 11 kwietnia 2018 w PHP przez _Visni4PL_ Obywatel (1,320 p.)
0 głosów
1 odpowiedź 729 wizyt
pytanie zadane 27 kwietnia 2017 w C i C++ przez Pabiak Gaduła (4,490 p.)
0 głosów
1 odpowiedź 170 wizyt
pytanie zadane 25 marca 2020 w JavaScript przez Skorpion Początkujący (360 p.)

93,334 zapytań

142,328 odpowiedzi

322,406 komentarzy

62,670 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

Wprowadzenie do ITsec, tom 1 Wprowadzenie do ITsec, tom 2

Można już zamawiać dwa tomy książek o ITsec pt. "Wprowadzenie do bezpieczeństwa IT" - mamy dla Was kod: pasja (użyjcie go w koszyku), dzięki któremu uzyskamy aż 15% zniżki! Dziękujemy ekipie Sekuraka za fajny rabat dla naszej Społeczności!

...