简体   繁体   English

如何在 javascript 测验中更改正确答案的颜色

[英]How to change the colour of the correct answer on a javascript quiz

I am making a javascript quiz: multiple choice with four options.我正在做一个 javascript 测验:有四个选项的多项选择。 When the answer is correct, I want it turn green before moving onto the next question, if incorrect I want it to turn red and the correct answer to flash green当答案正确时,我希望它在进入下一个问题之前变为绿色,如果不正确,我希望它变为红色并且 flash 的正确答案为绿色

Edits I have tried make the colour carry over into the next question.我尝试过的编辑使颜色延续到下一个问题。 Any suggestions?有什么建议么?

var currentQuestion =0;
var score = 0;
var totQuestions = questions.length;

var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');

function loadQuestion(questionIndex) {
var q = questions[questionIndex];
questionEl.textContent = (questionIndex +1)+ '.' + q.question;
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
opt4.textContent = q.option4;};


document.getElementById('opt1').onclick = function   loadNextQuestion    (){
var selectedOption = document.getElementById('opt1');

var answer = 1;
if(questions[currentQuestion].answer == answer){
score +=1;
}
selectedOption.clicked = false;
currentQuestion++;
if(currentQuestion == totQuestions - 1) {
nextButton.textContent = 'Finish';
 }
if (currentQuestion == totQuestions) {
container.style.display ='none';
resultCont.style.display = '';
resultCont.textContent = 'You scored ' + score;
return;
}
loadQuestion(currentQuestion);
}

Repeated three times four opt2, opt3 and opt 4重复 3 次 4 opt2、opt3 和 opt 4

This is solved via CSS.这是通过 CSS 解决的。 You can apply classes to your selected elements as the state requires.您可以按照 state 的要求将类应用于您选择的元素。 I'm not sure which element in your code represents a "correct" answer, but you would get a reference to that and add or remove a class as necessary.我不确定您的代码中的哪个元素代表“正确”的答案,但您会得到对它的引用,并根据需要添加或删除 class。 Ex:前任:

document.querySelector('.myCorrectAnswerElement').classList.add('greenSuccessClass');

Hope this sample will help you.希望这个样本对您有所帮助。

HTML: HTML:

<div id="item" > I am just a div</div>
    <button id="yes">yes</button>
    <button id="no">no</button>

CSS: CSS:

    #item{
    width: 500px;
    height: 30px;
    background-color: red;
}

JS: JS:

var item = document.getElementById("item");
var yes = document.getElementById("yes");
var no = document.getElementById("no");

yes.onclick = function(){
    item.style.backgroundColor = "red";
}

no.onclick = function(){
    item.style.backgroundColor = "green";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM