语法问题与js/jquery分配-测验问题在一个对象

syntax issues with js/jquery assignment - Quiz questions in an object

本文关键字:问题 一个对象 jquery js 语法 分配      更新时间:2023-09-26

我正试图通过一个任务来进一步了解js,但我遇到了一些问题,使我远离最终的代码。代码执行一个简短的测验——从单选按钮输入并与包含答案的对象匹配,然后输出最终分数。

代码http://jsfiddle.net/8ax9A/3/

我现在意识到的问题:我的$response变量似乎不起作用。
var $response = $('[name=rad]:checked').val();

计数器正在通过问题收听点击。在最后一个问题之后,我想报告最后的分数。我不能得到计数器达到问题+ 1的结束,我不能得到一个准确的最终分数监听器报告(var finalScore)。

 if ($response == parseInt(questions[counter].answer, 10)) {
            finalScore++;
        }

这些只是片段,所以请查看完整代码。我希望你能给我一些建议,告诉我哪里做错了。

你可以这样做:

//Initialization
var counter=0;
var score=0;
loadQuestion();
$('#next').on('click',answer);

//functions
function answer(){
    // if the user did not answer
    if ($('input:radio:checked').length == 0){
        alert('You have to answer!');
        return;
    }
    var currentQ=questions[counter];
    // if answer is correct
    if($('[name=rad]:checked').val()==currentQ.answer){score++;}
    counter++;
    // if there are no questions left
    if(counter >= questions.length) {displayResults(); return;}
    loadQuestion();
}
function loadQuestion(){
    // clear the radio buttons
    $("input:checked").removeAttr("checked");
    var currentQ=questions[counter];
    // display the question
    $('h1').text(currentQ.question);
    $('#a1').text(currentQ.choices[0]);
    $('#a2').text(currentQ.choices[1]);
    $('#a3').text(currentQ.choices[2]);
}
function displayResults(){
    $("h1").text("You've finished with a score of " + score + "!");
    $('[name=rad], #a1, #a2, #a3, #next').remove();
}

JS小提琴