gpt4 book ai didi

javascript - 多项选择测验 - 得分?

转载 作者:搜寻专家 更新时间:2023-10-31 22:06:11 24 4
gpt4 key购买 nike

我正在尝试用 HTML 创建一个简单的多项选择程序,但我在获取用户输入并在最后显示他们的分数时遇到了问题。有人可以帮帮我吗?

我的多项选择测验有 10 个问题,每个问题有 4 个选择。

例如有一个问题:

<li>
<h3>How many letters are there in "JS"?</h3>
<input type="radio" name="question9" value="A">2<br>
<input type="radio" name="question9" value="B">1<br>
<input type="radio" name="question9" value="C">3<br>
<input type="radio" name="question9" value="D">4<br>
</li>

这是我用来显示用户结果的按钮:

 <button onclick="returnScore()">View Results</button>

这是我当前的脚本:

var userInput = new Array();
var answers = new Array(10);
answers[0] = "B";
answers[1] = "C";
answers[2] = "A";
answers[3] = "C";
answers[4] = "D";
answers[5] = "D";
answers[6] = "D";
answers[7] = "D";
answers[8] = "C";
answers[9] = "A";

function getScore(){
var score=0;
var numQuestions=10;

for (var i=0;i<numQuestions;i++){
if (userInput[i]==answers[i]){
score += 1;
}
else{
score += 0;
}

}
return score;
}
function returnScore(){
alert("Your score is "+getScore()+"/10");
}

谢谢。

最佳答案

确保你的名字从 0 (question0) 开始,因为 for 循环内的 i0 索引。

您忘记循环您的 radio 元素(通过当前索引名称)以获取选中的元素的值:

var answers = ["A","C","B"], 
tot = answers.length;

function getCheckedValue( radioName ){
var radios = document.getElementsByName( radioName ); // Get radio group by-name
for(var y=0; y<radios.length; y++)
if(radios[y].checked) return radios[y].value; // return the checked value
}

function getScore(){
var score = 0;
for (var i=0; i<tot; i++)
if(getCheckedValue("question"+i)===answers[i]) score += 1; // increment only
return score;
}

function returnScore(){
alert("Your score is "+ getScore() +"/"+ tot);
}
<ul>
<li>
<h3>How many letters are there in "JS"?</h3>
<input type="radio" name="question0" value="A">2<br>
<input type="radio" name="question0" value="B">1<br>
<input type="radio" name="question0" value="C">3<br>
<input type="radio" name="question0" value="D">4<br>
</li>
<li>
<h3>How many letters are there in "BMX"?</h3>
<input type="radio" name="question1" value="A">2<br>
<input type="radio" name="question1" value="B">1<br>
<input type="radio" name="question1" value="C">3<br>
<input type="radio" name="question1" value="D">4<br>
</li>
<li>
<h3>How many letters are there in "A"?</h3>
<input type="radio" name="question2" value="A">2<br>
<input type="radio" name="question2" value="B">1<br>
<input type="radio" name="question2" value="C">3<br>
<input type="radio" name="question2" value="D">4<br>
</li>
</ul>

<button onclick="returnScore()">View Results</button>

您不需要为您的分数返回 += 0。如果你有一个积极的匹配,只需增加它。

当实例化新数组时,使用简写 [] 而不是 new Array()

关于javascript - 多项选择测验 - 得分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403558/

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