gpt4 book ai didi

javascript - 问答游戏,比较单选按钮的值来回答

转载 作者:行者123 更新时间:2023-12-02 22:57:07 24 4
gpt4 key购买 nike

我正在使用对象数组创建一个问答游戏。我创建了一个函数,它循环显示所有问题,然后循环所有选择并将它们变成单选按钮。我一直在努力将答案与所选值进行比较,因此当计时器用完时,我可以打印用户正确和错误的数量。有人能指出我正确的方向吗?

function countdown() {
var counter = 60;
var timeCountdown = setInterval(function(){

counter--
$('.timer-container .time').html(counter);
if (counter === 0) {
clearInterval(timeCountdown);
$('.timer-container .time').html("Times Up");
points();
}
}, 1000);

$('.timer-container').toggle();
}


let trivia = [
{
question: "How many wheels are on a skateboard?",
choices: ["2", "4", "6", "8"],
answer: "2",
},
{
question: "Who invented the kickflip?",
choices: ["Tony Hawk", "Bam Magera", "Rodney Mullen", "Chad Muska"],
answer: "Rodney Mullen"
},
{
question: "Who did the first 900?",
choices: ["Tony Hawk", "Tas Pappas", "Danny Way", "bob burnquist"],
answer: "Tony Hawk",
},
{
question: "What is another word for a 360 flip?",
choices: ["Impossible Flip", "3 1/2 flip", "Tre Bomb", "Tri Flip"],
answer: "Tre Bomb",
}
];


function triviaQuestions() {
for(var i = 0; i < trivia.length; i++) {

var questionHeader = $('<h2 class="question-' + i + '">');
var questionHeaderContent = questionHeader.text(trivia[i].question);
$('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + " '>");

for (var j = 0; j < trivia.length; j++) {
console.log(trivia[i].choices[j]);
var questionChoices = $('<input type="radio"' + 'name="' + i + '"'+ 'value="' + trivia[i].choices[j] + '">' + '<label>' + trivia[i].choices[j] + '</label>');
var questionChoicesContent = questionChoices.text(trivia[i].choices[j]);
$('.choices-container-' + i).append(questionChoices).append(questionChoicesContent);

}
}
}




$( document ).ready(function() {
$('.start-button').on('click', function() {
$(this).toggle();
countdown();
triviaQuestions();
});

});

谢谢

最佳答案

您的 points() 函数可能如下所示:

function points() {
var correct = 0;
$(".choices").each(function(i){
var questionid = $(this).attr('id').split('-')[1];
var answer = $(this).find("input:checked").val();
if (answer == trivia[questionid].answer) correct += 1;
});
$(".points-container").toggle();
$(".points-container span").text(correct);
}

假设您的页面上有一个元素,如下所示:

<div class="points-container" style="display:none">Total Points: <span></span></div>

并且假设您将 id="" 属性添加到表单元素中:

$('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + "' id='choices-" + i + "'>");

上面的函数循环遍历页面上的每个表单,从表单的 id 中提取问题在琐事数组中的索引,并将给出的答案与该索引中指定的答案进行匹配。也许不是最优雅的解决方案,但它对我有用,只需对代码进行最少的编辑。

关于javascript - 问答游戏,比较单选按钮的值来回答,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932212/

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