在将单选按钮值映射到 jquery 中的 json 数组中的值时需要帮助



我正在尝试读取选定的单选按钮并检查 JSON 中的匹配项。我正在使用jquery ajax来获取JSON数据,并尝试在单击"下一个问题"时以绿色突出显示正确答案,以红色突出显示错误答案。我正在循环中进行此检查,看起来因此无法正确满足条件。任何人都可以帮助找出错误所在吗?这是我的小提琴——

https://jsfiddle.net/ost2ypxj/4/

<body class="quiz">
<h1>Quiz on Important Facts</h1>
<div class="quiz-container">
<div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
</body>
$(document).ready(function(){
var quizContainer = $('#quiz');
var resultsContainer = $('#results');
var submitButton = $('#submit');
var output = [];
var mq ='';
const previousButton = $("#previous");
// const checkAnsweButton = $("#check");
const nextButton = $("#next");
var total = '';
var currentSlide = 0;

function buildQuiz(){ 
$.ajax({
url: './json/qa.json',
success: function(data){
//console.log(data.myQuestions);
mq = data.myQuestions;
mq.forEach(
(currentQuestion, questionNumber) => {
const answers = [];
for(letter in currentQuestion.answers){
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
output.push(
`<div class="slide">
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>
`
);
quizContainer.html(output.join(''));
const slides = $('#quiz').find(".slide");
total = slides.length;
showSlide(currentSlide);
});
}
})        
}
buildQuiz();

function showResults() {
// gather answer containers from our quiz
const answerContainers = quizContainer.find('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
mq.forEach((currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers.eq(questionNumber);
const selector = $('input[type=radio]:checked');
const userAnswer = (answerContainer.find(selector) || {}).val();
//console.log($('input[type=radio]:checked').val())
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) { 
// add to the number of correct answers
numCorrect++;
}
});
$(resultsContainer).html(`${numCorrect} out of ${mq.length}`);
}

function showSlide(n) {
//console.log(mq);
$('#quiz').find('.slide').eq(0).removeClass('active-slide');
$('#quiz').find('.slide').eq(n).addClass('active-slide');
$('#quiz').find('.slide').eq(n-1).removeClass('active-slide');
$('#quiz').find('.slide').eq(n+1).removeClass('active-slide');
currentSlide = n;
if (currentSlide === 0) {
previousButton.hide();
} else {
previousButton.show();
}
if (currentSlide === total - 1) {
nextButton.hide();
submitButton.show();
} else {
nextButton.show();
submitButton.hide();
}
}
var clickcount = 0;
function showNextSlide() {
const answerContainers = quizContainer.find('.answers');
if(clickcount == 2){
clickcount = 0;
}
if(clickcount == 0) {
console.log("next clicked once");
mq.forEach((currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers.eq(questionNumber);
const selector = $('input[type=radio]:checked');
const userAnswer = (answerContainer.find(selector) || {}).val();
//console.log(currentQuestion)
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) {
console.log("right answer") 
console.log("correctAnswer - "+currentQuestion.correctAnswer)
console.log("userAnswer - "+$('input[type=radio]:checked').val())
// color the answers green
answerContainers.find('input').eq(questionNumber).parent().css("color","lightgreen");
}
// if answer is wrong or blank
else {
console.log("wrong answer")
console.log("correctAnswer - "+currentQuestion.correctAnswer)
console.log("userAnswer - "+$('input[type=radio]:checked').val())
//
// color the answers red
answerContainers.find('input').eq(questionNumber).parent().css("color","red");
}
//answerContainers.find('input').eq(questionNumber).prop('disabled',true)
});
}
else {
console.log("next clicked second time");
showSlide(currentSlide + 1);
}

clickcount += 1;
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
submitButton.on('click', showResults);
previousButton.on("click", showPreviousSlide);
//checkAnsweButton.on('click', showResults);
nextButton.bind("click", showNextSlide);
})

{
"myQuestions" : [
{
"question": "Who invented JavaScript?",
"answers": {
"a": "Douglas Crockford",
"b": "Sheryl Sandberg",
"c": "Brendan Eich"
},
"correctAnswer": "c"
},
{
"question": "Which one of these is a JavaScript package manager?",
"answers": {
"a": "Node.js",
"b": "TypeScript",
"c": "npm"
},
"correctAnswer": "c"
},
{
"question": "Which tool can you use to ensure code quality?",
"answers": {
"a": "Angular",
"b": "jQuery",
"c": "RequireJS",
"d": "ESLint"
},
"correctAnswer": "d"
}
]
}

showNextSlide(( 函数是我试图突出显示正确/错误答案的地方

您当前的代码无法找到应用css的位置,因为您在 where 中使用 forloop并且它正在检查所有幻灯片而不是活动幻灯片。现在,为了在下面的代码中克服这个问题,我在问题div 中添加了attr,以便我们可以使用此 attr 来获取当前处于活动状态的当前问题,并且我们将用于从 json 数据中获取correctAnswer。另外,我还添加了input[type=radio]:checked,以便用户选择的单选按钮将仅更改所需的颜色greenred

演示代码

var data = {
"myQuestions": [{
"question": "Who invented JavaScript?",
"answers": {
"a": "Douglas Crockford",
"b": "Sheryl Sandberg",
"c": "Brendan Eich"
},
"correctAnswer": "c"
},
{
"question": "Which one of these is a JavaScript package manager?",
"answers": {
"a": "Node.js",
"b": "TypeScript",
"c": "npm"
},
"correctAnswer": "c"
},
{
"question": "Which tool can you use to ensure code quality?",
"answers": {
"a": "Angular",
"b": "jQuery",
"c": "RequireJS",
"d": "ESLint"
},
"correctAnswer": "d"
}
]
};
$(document).ready(function() {
var quizContainer = $('#quiz');
var resultsContainer = $('#results');
var submitButton = $('#submit');
var statusContainer = $('#status');
var output = [];
var mq = '';
const previousButton = $("#previous");
// const checkAnsweButton = $("#check");
const nextButton = $("#next");
var total = '';
var currentSlide = 0;
function buildQuiz() {
mq = data.myQuestions;
mq.forEach(
(currentQuestion, questionNumber) => {
const answers = [];
for (letter in currentQuestion.answers) {
answers.push(
`<label> <input type="radio" name="question${questionNumber}" value="${letter}">  ${letter} :
${currentQuestion.answers[letter]} </label>`);
}
output.push(`<div class="slide">
<div class="question" data-ques="${questionNumber}"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>  </div>  `); //^^ added data-ques attr to get curent question no
quizContainer.html(output.join(''));
const slides = $('#quiz').find(".slide");
total = slides.length;
showSlide(currentSlide);
});
}
buildQuiz();
function showResults() {
// gather answer containers from our quiz
const answerContainers = quizContainer.find('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
mq.forEach((currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers.eq(questionNumber);
const selector = $('input[type=radio]:checked');
const userAnswer = (answerContainer.find(selector) || {}).val();
//console.log($('input[type=radio]:checked').val())
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) {
// add to the number of correct answers
numCorrect++;
}
});
$(resultsContainer).html(`${numCorrect} out of ${mq.length}`);
}
function showSlide(n) {
//console.log(mq);
$('#quiz').find('.slide').eq(0).removeClass('active-slide');
$('#quiz').find('.slide').eq(n).addClass('active-slide');
$('#quiz').find('.slide').eq(n - 1).removeClass('active-slide');
$('#quiz').find('.slide').eq(n + 1).removeClass('active-slide');
currentSlide = n;
if (currentSlide === 0) {
previousButton.hide();
} else {
previousButton.show();
}
if (currentSlide === total - 1) {
nextButton.hide();
submitButton.show();
} else {
nextButton.show();
submitButton.hide();
}
}
var clickcount = 0;
function showNextSlide() {
let percentage = 0;
let numCorrect = 0;
const answerContainers = quizContainer.find('.answers');
let currentques = $('#quiz').find('.active-slide');
if (clickcount == 2) {
clickcount = 0;
}
//to find which question is user on
var ques_no = currentques.find(".question").attr("data-ques");
if (clickcount == 0) {
// find selected answer
const answerContainer = answerContainers.eq(ques_no);
const selector = $('input[type=radio]:checked');
const userAnswer = (answerContainer.find(selector) || {}).val();
// if answer is correct
if (userAnswer === mq[ques_no].correctAnswer) {
numCorrect++;
// color the answers green and added green to checked radio button
answerContainers.find('input[type=radio]:checked').eq(ques_no).parent().css("color", "lightgreen");
percentage = Math.round(((numCorrect / mq.length) * 100))
}
// if answer is wrong or blank
else {
// color the answers red and added checked radio button to color red
answerContainers.find('input[type=radio]:checked').eq(ques_no).parent().css("color", "red");
}
} else {
showSlide(currentSlide + 1);
$(statusContainer).html(`Your test is ${percentage} % compelete`);
}
clickcount += 1;
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
//added clicked event to call function on last question as well
submitButton.on('click', showNextSlide);
submitButton.on('click', showResults);
previousButton.on("click", showPreviousSlide)
nextButton.bind("click", showNextSlide);
})
@import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);
body {
font-size: 20px;
font-family: 'Work Sans', sans-serif;
color: #333;
font-weight: 300;
text-align: center;
background-color: #f8f6f0;
}
h1 {
font-weight: 300;
margin: 0px;
padding: 10px;
font-size: 20px;
background-color: #444;
color: #fff;
}
.question {
font-size: 30px;
margin-bottom: 10px;
}
.answers {
margin-bottom: 20px;
text-align: left;
display: inline-block;
}
.answers label {
display: block;
margin-bottom: 10px;
}
button {
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #279;
color: #fff;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-bottom: 20px;
}
button:hover {
background-color: #38a;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
z-index: 1;
opacity: 0;
transition: opacity 0.5s;
}
.active-slide {
opacity: 1;
z-index: 2;
}
.quiz-container {
position: relative;
height: 230px;
margin-top: 70px;
}
#result {
font-size: 50px;
}
<script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.js"></script>
<body class="quiz">
<h1>Quiz on Important Facts</h1>
<div class="quiz-container">
<div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
</body>

此外,上面的代码有一个缺陷,当它到达最后一个问题并单击提交按钮时,问题将从开始开始停止,您添加一个计数器,该计数器将检查最后一个问题何时到达。

最新更新