如果选择了不正确的单选选项,为什么if语句中的else仍然出现? else部分应仅在未选择单选按钮时出现。真正的结果是下一个问题和可能出现的答案。这是jsfiddle。我究竟做错了什么?
function checkAnswer(){
submit.onclick = function(){
var radios = document.getElementsByName('choices');
var i = 0;
var len = radios.length;
while(i<len){
if(radios[i].checked){
if(radios[i].id == allQuestions[0].correctAnswer){
userScore++;
alert("curent score:" + userScore);
break;
}
}else{
alert("Please selected an option");
break;
}
i++
}
}
}
最佳答案
您正在遍历所有单选按钮。如果大于1,则可以确保未选择其中至少一个,因此您将进入else
。尝试这个:
function checkAnswer(){
submit.onclick = function(){
var radios = document.getElementsByName('choices');
var i = 0;
var len = radios.length;
var foundSelected = false;
while(i<len){
if(radios[i].checked){
foundSelected = true;
if(radios[i].id == allQuestions[0].correctAnswer){
userScore++;
alert("curent score:" + userScore);
break;
}
}
i++
}
if (!foundSelected)
alert("Please selected an option");
}
}