gpt4 book ai didi

javascript - 测验 - if 语句

转载 作者:行者123 更新时间:2023-11-30 08:41:19 28 4
gpt4 key购买 nike

为什么选择不正确单选选项时,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");
}
}

关于javascript - 测验 - if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26145272/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com