我有一个功能,可以根据选择的选项来计算调查中的分数,但如果条件为第一个,我总是得到相同的值 各种问题= [{ “ question”:“ L'impest est”, 选项1:“可靠”, option2:“ moyen”, option3:“小屋”, },
var currentQuestion = 0;
var score1 = 0;
var totQuestions = questions.length;
var number = 0;
var progressText = document.getElementById("progressText");
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 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;
progressText.innerText = questionIndex + 1 + ' de ' + totQuestions + '
questions ';
};
function loadNextQuestion() {
var selectedOption =
document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert('veuillez sélectionner votre réponse');
return;
}
var answer =selectedOption.Value;
if (questions[currentQuestion].opt1 == answer) {
score1 += 1;
} else if (questions[currentQuestion].opt2 == answer) {
score1 += 2;
} else {
score1 += 3
}
selectedOption.checked = false;
currentQuestion++;
progressText.textContent = questionEl / totQuestions
if (currentQuestion == totQuestions - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totQuestions) {
container.style.display = 'none';
resultCont.style.display = '';
resultCont.textContent = 'le résultat est ' + ' ' + score1 + ' '
+answer+' '+ option1 ;
return;
}
loadQuestion(currentQuestion);
};
loadQuestion(currentQuestion);
答案 0 :(得分:0)
如果我对您的理解很好,那么您的问题可能是由于以下另一个原因:
<select>
元素上触发更改事件。answer
的值,您可能需要使用.selectedIndex
来获得答案的值。看看 onchange Event,.selectedIndex
var questions = [{
opt1: "Answer 1",
opt2: "Answer 2",
opt3: "Answer 3"
}];
// score1, currentQuestion variables defined as example
var currentQuestion = 0;
var score1 = 1;
var sel = document.getElementById("sel");
sel.addEventListener("change", function() {
var answer = this.options[this.selectedIndex].value;
if (questions[currentQuestion].opt1 == answer) {
score1 += 1;
} else if (questions[currentQuestion].opt2 == answer) {
score1 += 2;
} else {
score1 += 3;
}
console.log("score1 = " + score1)
});
<div id="q"></div>
<select id="sel">
<option value="Answer 1">Answer 1</option>
<option value="Answer 2">Answer 2</option>
<option value="Answer 3">Answer 3</option>
</select>