すべての質問の状態を追跡し、すべての関数でその状態を調査します。
// question 1 is questionState[0], 2 is questionState[1], etc
var questionState = [false, false, false, false];
var allCorrect = function () {
for (var i = 0; i < questionState.length; i++) {
if (!questionState[i]) {
return false;
}
}
return true;
};
var changecolour1 = function (textbox) {
var val = textbox.value;
if (val == 26) {
questionState[0] = true;
textbox.style.backgroundColor = 'green';
if (allCorrect()) {
alert('Congratulations!');
}
} else {
questionState[0] = false;
textbox.style.backgroundColor = 'red';
}
};
changecolour
おそらく、4 つの関数すべてを 1 つの汎用関数に置き換えることができることに注意してください。これは、テキスト ボックスに対応する ID があることを前提としています。
var questions = {
textbox1: {
answer: 26,
state: false
},
textbox2: {
answer: 0,
state: false
},
textbox3: {
answer: 1,
state: false
},
textbox4: {
answer: 2,
state: false
},
};
var allCorrect = function () {
for (var i = 0; i < questions.length; i++) {
if (!questions[i].state) {
return false;
}
}
return true;
};
var changecolour = function (textbox) {
var val = textbox.value;
if (val == questions[textbox.id].answer) {
questions[textbox.id].state = true;
textbox.style.backgroundColor = 'green';
if (allCorrect()) {
alert('Congratulations!');
}
} else {
questions[textbox.id].state = false;
textbox.style.backgroundColor = 'red';
}
};