我正在做一个JavaScript测验:有四个选项的多项选择。答案正确时,我希望它变成绿色,然后再继续下一个问题;如果答案不正确,我希望它变成红色,而正确的答案则闪烁绿色
我尝试过的编辑使颜色保留到下一个问题中。有什么建议吗?
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);
}
四个opt2,opt3和opt 4重复三遍
答案 0 :(得分:0)
这是通过CSS解决的。您可以根据状态要求将类应用于所选元素。我不确定代码中的哪个元素代表“正确”的答案,但是您将获得对此的引用并根据需要添加或删除类。例如:
document.querySelector('.myCorrectAnswerElement').classList.add('greenSuccessClass');
答案 1 :(得分:0)
希望此示例对您有帮助。
HTML:
<div id="item" > I am just a div</div>
<button id="yes">yes</button>
<button id="no">no</button>
CSS:
#item{
width: 500px;
height: 30px;
background-color: red;
}
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";
}