我是HTML和JavaScript的新手,我试图编写函数解决方案,返回一个整数分数,验证用户选择的复选框有多少是正确的。函数should_be_checked(question_index,choice_index)已经定义,如果答案正确,则返回true,否则返回false。我希望在我的解决方案函数中使用函数should_be_checked来评估分数。如何从HTML表单中获取数组中的输入值,然后使用数组值与来自should_be_checked函数的正确值生成分数。例如:如果我执行should_be_checked(2,2),它将返回true,因为它是正确的答案。question_index和choice_index是作为参数传递给should_be_checked函数的值。一旦用户选择复选框,解决方案()函数将在单击按钮上被调用。
function solution() {
var score = 0;
$("input[type=checkbox]").each(checkbox => {
let args = checkbox.attr("id").split("-"); // Split at the dashes to get an array containing ["choice", "1", "2"]
args.shift() // Remove the first element that says "choice"
if (checkbox.prop("checked") !== should_be_checked(...args)) {
score = score + 1; // Increment the score
});
return score;
}<form>
<fieldset id="question-1">
<legend>Easy question</legend>
<input type="checkbox" id="choice-1-1" checked>Incorrect answer</input>
</fieldset>
<fieldset id="question-2">
<legend>Another sample question</legend>
<input type="checkbox" id="choice-2-1">Sample incorrect answer</input><br>
<input type="checkbox" id="choice-2-2" checked="checked">Sample correct answer</input>
</fieldset>
</form>
发布于 2018-05-04 18:14:47
如果循环遍历每个复选框,则可以检查是否应该使用函数检查它们。
let allQuestionsCorrect = true;
$("input[type=checkbox]").each(checkbox => {
let args = checkbox.attr("id").split("-"); // Split at the dashes to get an array containing ["choice", "1", "2"]
args.shift() // Remove the first element that says "choice"
if(checkbox.prop("checked") !== should_be_checked(...args)) {
allQuestionsCorrect = false; // If it shouldn't be checked and it is or should be checked and it isn't, the questions are not all correct
}
});
return allQuestionsCorrect如果检查的属性不是应该返回的属性,则返回false
https://stackoverflow.com/questions/50180783
复制相似问题