跟踪所有问题的状态,并在每个函数中询问该状态:
// 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 个函数。这假设您的文本框具有相应的 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';
}
};