测验记录正确答案的问题和答案突出显示绿色的问题

时间:2019-08-23 05:28:56

标签: javascript jquery html css

我是编码的新手,我的测验应用程序有一些问题。首先,在通过添加单选按钮更改代码后,由于某种原因,我的测验不再记录正确的答案,并且得分仍然为0。此外,我想保持相同的状态

const myQuestions = [{
    'question': 'WHAT IS THE OFFICE AWARDS NIGHT CALLED?',
    'answers': ["DORKIES", "DUNDIES", "DWEEBIES", "DINGLES"],
    'correct': 1
  },
  {
    'question': 'WHAT IS THE GIANT POT THAT KEVIN DROPS ALL OVER THE OFFICE FLOOR?',
    'answers': ["GRAVY", "SOUP", "MAC & CHEESE", "CHILI"],
    'correct': 3
  },
  {
    'question': "HOW LONG HAD JIM AND PAM BEEN DATING BEFORE HE BOUGHT HER ENGAGEMENT RING",
    'answers': ["ONE WEEK", "ONE MONTH", "ONE YEAR", "TWO YEARS"],
    'correct': 0
  },
  {
    'question': "WHAT DOES MICHAEL CHOOSE AS HIS USERNAME WHEN HE SIGNS UP FOR AN ONLINE DATING SITE?",
    'answers': ["LITTLEKIDLOVER", "IAMTHEBOSS", "DUNDERMIFF", "READYFORMARRIAGE"],
    'correct': 0
  },
  {
    'question': "WHAT IS ERIN'S REAL FIRST NAME?",
    'answers': ["BRITTANY", "CHRISTINE", "BECCA", "KELLY"],
    'correct': 3
  },
  {
    'question': "WHICH COUNTRY DOES TOBY MOVE TO WHEN HE LEAVES HIS JOB AT DUNDER MIFLIN ONLY TO RETURN LATER?",
    'answers': ["JAMAICA", "COSTA RICA", "ITALY", "CUBA"],
    'correct': 1
  },
  {
    'question': "DWIGHT AND ANDY HAVE A DUEL OVER WHICH WOMAN IN THE OFFICE?",
    'answers': ["ANGELA", "ERIN", "KELLY", "MEREDITH"],
    'correct': 0
  },
  {
    'question': "WHAT IS THE NAME OF THE CAT THAT ANGELA THROWS AT OSCAR DURING THE FIRE DRILL?",
    'answers': ["SPRINKLES", "CUPCAKE", "BANDIT", "TINKERBELL"],
    'correct': 2
  },
  {
    'question': "WHAT DOES JAN NAME THE BABY SHE HAS VIA SPERM DONOR?",
    'answers': ["AXON", "ALLY", "APPLE", "ASTRID"],
    'correct': 3
  },
  {
    'question': "HOW MANY KIDS DO PAM AND JIM HAVE?",
    'answers': ["3", "2", "1", "0"],
    'correct': 1
  }];

let score = 0;
let current = 0;
$(document).ready(function() {
  // start button event listener
  $(".start-button").click(function() {
    $('.start-page').hide();
    $('.next').hide();
    $('.questions').show();
    displayQuestion();
    $('.score').text('Current Score: ' + score);
    console.log("Start Quiz button clicked");
  });
  // next button event listener
  $(".next-button").click(function(event) {
    console.log("Next button clicked");
    displayQuestion();
    $('.next').hide();
    $('.submit').show();
  });
  $(".submit-button").click(function(event) {
    event.preventDefault();
    var selected = $('input.selected');
    console.log(event);
    if (selected.length) {
      let answer = $('input.selected').attr('id');
      console.log(answer);
      checkAnswer(answer);
      console.log("hey world");
      $('.next').show();
      $('.submit').hide();
    } else {
      alert('Please select an answer');
    }
  });
  // retry button click listener
  $(".retry-button").click(function() {
    location.reload();
    console.log("Retake button clicked");
  });
  //click listener to make questions change color on hover
  $('div.questions-selector').on('click', 'input', function(event) {
    $('.selected').removeClass();
    $(this).addClass('selected');
  });
});

//FUNCTIONS
function displayQuestion() {
  $('.question-number').text('Question Number: ' + (current + 1) + "/10");

  if (current < myQuestions.length) {
    let listQuestion = myQuestions[current];
    $('h2').text(listQuestion.question);
    $('div.questions-selector').html('');
    for (let i = 0; i < listQuestion.answers.length; i++) {
      $('div.questions-selector').append(`<div><label 
       for"input${i}">${listQuestion.answers[i]}</label>
        <input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
    }
  } else {
    // show summary that says how many you got correct
    displayScore();
  }
}

// function stub to check answer
function checkAnswer(answer) {
  let listQuestion = myQuestions[current];
  if (listQuestion.correct == answer) {
    score++;
    $('label.selected').addClass('correct');
  } else {
    $('label.selected').addClass('incorrect');
  }
  $('.score').text('Current Score: ' + score);
  current++;
}

//function to display score
function displayScore() {
  $('.questions').hide();
  $('.end-quiz').show();
  $('.end-score').text("Your score: " + score + '/10');
  if (score >= 7) {
    $('.comment').text('Nice job, Superfan!');
  } else {
    $('.comment').text('Get to binge watching and try again!')
  }
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: #586060;
  background-repeat: no-repeat;
  background-size: cover;
  font-family: 'Mina', sans-serif;
  color: white;
  font-size: 20px;
  margin: 10px;
}

.topbar {
  max-width: 800px;
  margin-top: 20px;
  font-size: 12px;
  padding-bottom: 30px;
  font-weight: bold;
  color: white;
}

h1,
h2 {
  text-align: center;
  font-weight: bold;
  color: white;
  display: block;
}

h2 {
  font-size: 20px;
  color: white;
  display: block;
}

button {
  width: 300px;
  height: 40px;
  background: #d4f4dd;
  font-family: 'Mina', sans-serif;
  font-size: 20px;
  font-weight: 300;
  color: #424b54;
  border: 2px solid #d4f4dd;
}

.start-page {
  width: 500px;
  height: 300px;
  margin: 10px auto;
  text-align: center;
  padding-bottom: 200px;
  color: white;
}

.questions,
.end-quiz {
  display: none;
  text-align: center;
  padding-bottom: 0px;
  margin: 0 auto 0 auto;
  text-align: center;
  width: 500px;
  height: 300px;
  min-height: 300px;
}

.end-quiz {
  padding-top: 80px;
  height: 100px;
  font-size: 30px;
  color: white;
}

.question-number,
.score {
  font-size: 30px;
  color: white;
  padding-top: 0px;
}

.div {
  list-style: none;
  padding: 0;
}

.input {
  border: 1px solid #d6d6cf;
  width: 200px;
  margin: 5px auto;
  font-size: 18px;
  border-radius: 5px;
  padding: 5px;
}

.selected {
  background: #f2b632;
  color: #252839;
}

.correct {
  background-color: lightgreen;
}

.incorrect {
  background-color: red;
}

@media screen and (min-width: 300px) {
  .topbar {
    width: 50%;
    margin: auto;
    padding-top: 30px;
    font-size: 20px;
  }
  .questions .end-quiz {
    width: 200px;
    margin: 0 auto;
  }
}

@media screen and (min-width: 600px) {
  .topbar {
    width: 80%;
    font-size: 40px;
    margin: 0 auto;
  }
  .questions .end-quiz {
    width: 400px;
    margin: 0 auto;
  }
}

@media screen and (max-width: 900px) {
  .topbar {
    font-size: 60px;
    font-weight: bold;
    margin: 0 auto;
  }
}

.questions .end-quiz {
  width: 600px;
  margin: 0 auto;
}


}
fieldset {
  min-height: 300px;
}

}
.label {
  display: block;
}

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <!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="./float-grid.css" />
 <link rel="stylesheet" href="index.css">
 <link href="https://fonts.googleapis.com/css?family=Mina" 
  rel="stylesheet">
 <title>Quiz App</title>

</head>

<body>
<main>

   <!--Section 1 WELCOME-->
   <h1 class="topbar"><marquee behavior="alternate">The Office 
   Quiz</marquee></h1>
  
 

  <div class="start-page">
  <p>Are you a true fan of The Office? Let's find out!</p>
  <button value="start" type="start" class="start-button">Begin 
  Quiz</button>
</div>


  <!--Section 2 QUESTIONS-->

  <form class="questions">
  <fieldset>
   <Legend>
   <h2 class="question"></h2></Legend>
   <div class="questions-selector"></div>
    <div class="submit">
    <button value="submit" type="submit" class="submit-button">Check 
Your Answer</button>
    </div>
  </fieldset>
 </form>
<div class="questions">
  <div class="next">
    <button value="next" type="next" class="next-button">Next 
Question</button>
  </div>
  <p class="score">Score:</p>
  <p class="question-number"></p>
</div>
   
<!--SECTION 3 RESULTS-->

<section class='end-quiz'>
  <p class='end-score'></p>
  <p class='comment'></p>
  <button value="retry" type="retry" class="retry-button">Retake 
Quiz</button>
</section>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="index.js"></script>
   </body>
 
</html>

垫子,但是,我不需要按钮,因为我希望它以绿色突出显示正确的答案。

3 个答案:

答案 0 :(得分:1)

您的代码有些混乱,我为自己的改进而感到自豪,但是我进行了更改,并且代码再次正常工作。查看我的更改:

  1. 在功能displayQuestions中,我向单选按钮(ans)添加了新属性

    <input type="radio" **ans=${i}** name="choice" value="0" id = "input${i}"> 
    </input></div>`)
    
  2. $(.submit-button)我添加了任务变量,并且更改了答案变量

    $(".submit-button").click(function(event) {
       event.preventDefault();
       var selected = $('input.selected');
       if (selected.length) {
         **let answer = $('input.selected').attr('ans');**
         **let quest = $('input.selected').attr('id');**
         **checkAnswer(answer,quest);**
         $('.next').show();
         $('.submit').hide();
      } else {
        alert('Please select an answer');
      }
    });
    
  3. 我更改了checkAnswer功能

    function checkAnswer(answer,question) {
      let listQuestion = myQuestions[current];
      if (listQuestion.correct === Number.parseInt(answer)) {
        score++;
        document.getElementById(question).previousElementSibling.classList.add('correct');
     } else {
       document.getElementById(question).previousElementSibling.classList.add('incorrect')
     }
        $('.score').text('Current Score: ' + score);
        current++;
     }
    

我希望这会对您有所帮助。祝你好运!

答案 1 :(得分:0)

此功能缺少一些内容。

function displayQuestion() {
  $('.question-number').text('Question Number: ' + (current + 1) + "/10");

  if (current < myQuestions.length) {
    let listQuestion = myQuestions[current];
    $('h2').text(listQuestion.question);
    $('div.questions-selector').html('');
    for (let i = 0; i < listQuestion.answers.length; i++) {
      $('div.questions-selector').append(`<div><label 
       for"input${i}">${listQuestion.answers[i]}</label>
        <input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
    }
  } else {
    // show summary that says how many you got correct
    displayScore();
  }
}

您应该修复此部分。

<input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)

此输入$ {i}是您无法获得正确答案的原因。只需将您的代码修改为这样。

<input type="radio" name="choice" value="0" id = "${i}"></input></div>`)

答案 2 :(得分:0)

您已经接近,但是错过了几件事:

  • 您正在(通过类)设置输入的样式,而不是使用jQuery流程设置所选标签的样式,这使得背景更改很难看到
  • 在您的checkAnswer函数中,您实际上并没有在比较两个相同的东西,这会导致条件测试失败

请参阅修改后的代码以进行某些工作(请注意,其样式是 div 的样式,而不是 label 的样式,我让您知道了)。您可以搜索下方的修改标签以查看触摸的位置。

const myQuestions = [{
    'question': 'WHAT IS THE OFFICE AWARDS NIGHT CALLED?',
    'answers': ["DORKIES", "DUNDIES", "DWEEBIES", "DINGLES"],
    'correct': 1
  },
  {
    'question': 'WHAT IS THE GIANT POT THAT KEVIN DROPS ALL OVER THE OFFICE FLOOR?',
    'answers': ["GRAVY", "SOUP", "MAC & CHEESE", "CHILI"],
    'correct': 3
  },
  {
    'question': "HOW LONG HAD JIM AND PAM BEEN DATING BEFORE HE BOUGHT HER ENGAGEMENT RING",
    'answers': ["ONE WEEK", "ONE MONTH", "ONE YEAR", "TWO YEARS"],
    'correct': 0
  },
  {
    'question': "WHAT DOES MICHAEL CHOOSE AS HIS USERNAME WHEN HE SIGNS UP FOR AN ONLINE DATING SITE?",
    'answers': ["LITTLEKIDLOVER", "IAMTHEBOSS", "DUNDERMIFF", "READYFORMARRIAGE"],
    'correct': 0
  },
  {
    'question': "WHAT IS ERIN'S REAL FIRST NAME?",
    'answers': ["BRITTANY", "CHRISTINE", "BECCA", "KELLY"],
    'correct': 3
  },
  {
    'question': "WHICH COUNTRY DOES TOBY MOVE TO WHEN HE LEAVES HIS JOB AT DUNDER MIFLIN ONLY TO RETURN LATER?",
    'answers': ["JAMAICA", "COSTA RICA", "ITALY", "CUBA"],
    'correct': 1
  },
  {
    'question': "DWIGHT AND ANDY HAVE A DUEL OVER WHICH WOMAN IN THE OFFICE?",
    'answers': ["ANGELA", "ERIN", "KELLY", "MEREDITH"],
    'correct': 0
  },
  {
    'question': "WHAT IS THE NAME OF THE CAT THAT ANGELA THROWS AT OSCAR DURING THE FIRE DRILL?",
    'answers': ["SPRINKLES", "CUPCAKE", "BANDIT", "TINKERBELL"],
    'correct': 2
  },
  {
    'question': "WHAT DOES JAN NAME THE BABY SHE HAS VIA SPERM DONOR?",
    'answers': ["AXON", "ALLY", "APPLE", "ASTRID"],
    'correct': 3
  },
  {
    'question': "HOW MANY KIDS DO PAM AND JIM HAVE?",
    'answers': ["3", "2", "1", "0"],
    'correct': 1
  }];

let score = 0;
let current = 0;
$(document).ready(function() {
  // start button event listener
  $(".start-button").click(function() {
    $('.start-page').hide();
    $('.next').hide();
    $('.questions').show();
    displayQuestion();
    $('.score').text('Current Score: ' + score);
    console.log("Start Quiz button clicked");
  });
  // next button event listener
  $(".next-button").click(function(event) {
    console.log("Next button clicked");
    displayQuestion();
    $('.next').hide();
    $('.submit').show();
  });
  $(".submit-button").click(function(event) {
    event.preventDefault();
    var selected = $('input.selected');
    //console.log(event);
    if (selected.length) {
      let answer = $('input.selected').attr('id');
      console.log("answer: " + answer);
      checkAnswer(answer);
      $('.next').show();
      $('.submit').hide();
    } else {
      alert('Please select an answer');
    }
  });
  // retry button click listener
  $(".retry-button").click(function() {
    location.reload();
    console.log("Retake button clicked");
  });
  //click listener to make questions change color on hover
  $('div.questions-selector').on('click', 'input', function(event) {
    $('.selected').removeClass();
    $(this).addClass('selected');

    // MODIFICATIONS BELOW
    $(this).parent().addClass('selected');
  });
});

//FUNCTIONS
function displayQuestion() {
  $('.question-number').text('Question Number: ' + (current + 1) + "/10");

  if (current < myQuestions.length) {
    let listQuestion = myQuestions[current];
    $('h2').text(listQuestion.question);
    $('div.questions-selector').html('');
    for (let i = 0; i < listQuestion.answers.length; i++) {
      $('div.questions-selector').append(`<div><label 
       for"input${i}">${listQuestion.answers[i]}</label>
        <input type="radio" name="choice" value="0" id = "input${i}"></input></div>`)
    }
  } else {
    // show summary that says how many you got correct
    displayScore();
  }
}

// function stub to check answer
function checkAnswer(answer) {
  let listQuestion = myQuestions[current];

  // MODIFICATIONS BELOW
  const inputString = "input";
  const correctId = inputString.concat(listQuestion.correct);
  console.log("correctId: " + correctId);
  if (correctId == answer) {
    score++;
  } else {
    $('#'+answer).parent().addClass('incorrect');
  }
  $('#'+correctId).parent().addClass('correct');
  $('.score').text('Current Score: ' + score);
  current++;
}

//function to display score
function displayScore() {
  $('.questions').hide();
  $('.end-quiz').show();
  $('.end-score').text("Your score: " + score + '/10');
  if (score >= 7) {
    $('.comment').text('Nice job, Superfan!');
  } else {
    $('.comment').text('Get to binge watching and try again!')
  }
};
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: #586060;
  background-repeat: no-repeat;
  background-size: cover;
  font-family: 'Mina', sans-serif;
  color: white;
  font-size: 20px;
  margin: 10px;
}

.topbar {
  max-width: 800px;
  margin-top: 20px;
  font-size: 12px;
  padding-bottom: 30px;
  font-weight: bold;
  color: white;
}

h1,
h2 {
  text-align: center;
  font-weight: bold;
  color: white;
  display: block;
}

h2 {
  font-size: 20px;
  color: white;
  display: block;
}

button {
  width: 300px;
  height: 40px;
  background: #d4f4dd;
  font-family: 'Mina', sans-serif;
  font-size: 20px;
  font-weight: 300;
  color: #424b54;
  border: 2px solid #d4f4dd;
}

.start-page {
  width: 500px;
  height: 300px;
  margin: 10px auto;
  text-align: center;
  padding-bottom: 200px;
  color: white;
}

.questions,
.end-quiz {
  display: none;
  text-align: center;
  padding-bottom: 0px;
  margin: 0 auto 0 auto;
  text-align: center;
  width: 500px;
  height: 300px;
  min-height: 300px;
}

.end-quiz {
  padding-top: 80px;
  height: 100px;
  font-size: 30px;
  color: white;
}

.question-number,
.score {
  font-size: 30px;
  color: white;
  padding-top: 0px;
}

.div {
  list-style: none;
  padding: 0;
}

.input {
  border: 1px solid #d6d6cf;
  width: 200px;
  margin: 5px auto;
  font-size: 18px;
  border-radius: 5px;
  padding: 5px;
}

.selected {
  background: #f2b632;
  color: #252839;
}

div.correct {
  background-color: lightgreen;
}

div.incorrect {
  background-color: red;
}

@media screen and (min-width: 300px) {
  .topbar {
    width: 50%;
    margin: auto;
    padding-top: 30px;
    font-size: 20px;
  }
  .questions .end-quiz {
    width: 200px;
    margin: 0 auto;
  }
}

@media screen and (min-width: 600px) {
  .topbar {
    width: 80%;
    font-size: 40px;
    margin: 0 auto;
  }
  .questions .end-quiz {
    width: 400px;
    margin: 0 auto;
  }
}

@media screen and (max-width: 900px) {
  .topbar {
    font-size: 60px;
    font-weight: bold;
    margin: 0 auto;
  }
}

.questions .end-quiz {
  width: 600px;
  margin: 0 auto;
}


}
fieldset {
  min-height: 300px;
}

}
.label {
  display: block;
}

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <!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="./float-grid.css" />
 <link rel="stylesheet" href="index.css">
 <link href="https://fonts.googleapis.com/css?family=Mina" 
  rel="stylesheet">
 <title>Quiz App</title>

</head>

<body>
<main>

   <!--Section 1 WELCOME-->
   <h1 class="topbar"><marquee behavior="alternate">The Office 
   Quiz</marquee></h1>
  
 

  <div class="start-page">
  <p>Are you a true fan of The Office? Let's find out!</p>
  <button value="start" type="start" class="start-button">Begin 
  Quiz</button>
</div>


  <!--Section 2 QUESTIONS-->

  <form class="questions">
  <fieldset>
   <Legend>
   <h2 class="question"></h2></Legend>
   <div class="questions-selector"></div>
    <div class="submit">
    <button value="submit" type="submit" class="submit-button">Check 
Your Answer</button>
    </div>
  </fieldset>
 </form>
<div class="questions">
  <div class="next">
    <button value="next" type="next" class="next-button">Next 
Question</button>
  </div>
  <p class="score">Score:</p>
  <p class="question-number"></p>
</div>
   
<!--SECTION 3 RESULTS-->

<section class='end-quiz'>
  <p class='end-score'></p>
  <p class='comment'></p>
  <button value="retry" type="retry" class="retry-button">Retake 
Quiz</button>
</section>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="index.js"></script>
   </body>
 
</html>