0

スクリプトのエラーを見つけようとしていますが、どこが間違っているのか誰かが教えてくれることを願っています。JS/Jquery (javascriptissy 演習) に基づいてクイズを作成する試みです。

これまでのところ、問題なく動作していますが、次の点を除きます。ユーザーからの以前の回答を呼び出し、それに応じてラジオ ボタンを設定する戻るボタンを使用したいと考えています。スクリプトは戻りません。進むをクリックしても、問題を特定するのに役立つエラーは表示されません。

繰り返しますが、どの部分が関連しているか、関連していないのか本当にわからないため、これ以上絞り込めないことを本当に申し訳ありません。「問題を特定する方法がわからないため、あきらめようとしています」という問題をより良い方法で提示する方法を誰かが提案している場合は、喜んでそうします。

HTML ラジオ ボタンはすべて次のような構造になっています。

 <input type="radio" name="radio" id="Option0" value="Option0" />
 <label for ="Option0">Option0</label>

JS/Jquery:

 $(document).ready(function () {
 var allQuestions = [
    {question: "Who is Prime Minister of the United Kingdom?",
        choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
        correctAnswer: 0},
    {question: "Which color has the sky?",
        choices: ["Grey", "Black", "Blue", "Green"],
        correctAnswer: 2},
    {question: "What's on the chain?",
        choices: ["Monster", "Magician", "Bull", "Skull"],
        correctAnswer: 3}
];

var counter = 0;     // Question No currently processed
var points = 0;        // Total points currently reached by the player
var answers = new Array(); // Array of the choices the player made  eg Q1:0

// Back button in a function
function back() {
    if (counter > 0)          //Checks if there is at least one question already answered
    {
        //Goes back one question

        $("#back").show().on('click', function () {
            counter = counter--;
            quiz();
        });      //Executes quiz loading

    }
    else {
        $("#back").hide();         //If there is no previous question existing the back button is deactivated
    }
}


function qload(counter) {
    $("title").text("Question No ");
    $("#question").text(allQuestions[counter].question);
    back();
    for (var i = 0; i < allQuestions[counter].choices.length; i++) {
        $('label[for=Option' + i + ']').html(allQuestions[counter].choices[i]);

        if (answers["Q" + i]) {
            $("#Option" + i).attr("checked","checked");
        }

        else {
            $("#Option" + i).removeAttr('checked');
        }
    }
};
//this is the result screen giving the final amount of points
function result() {
    $("title").text("Your Results");
    for (var i = 0; i < allQuestions.length; i++) {
        if (allQuestions[i].correctAnswer == answers["Q" + i]) {
            points++;
        }


        $("#result").show().text("CONGRATULATIONS! You answered " + points + " out of " + allQuestions.length + " correct!");
        $(".qbox").hide();
        console.log(answers);

    }
}

function welcome() {
    // this is the welcome screen inviting to start the quizz
    $("title").text("Welcome to the JQuery QuizY");
    $(".qbox").hide();
    $("#result").append().html("Random");
    $("#result").append().html("<p id='start'>Start</p>");
    $("#start").on('click', function () {
        quiz();
    });
}

function quiz() {
    $("#start, #result").hide();
    $(".qbox").show();
    qload(counter);
    $("#next").on('click', function () {
        // this checks that one question is selected before processing
        if ($('#Option0').is(':checked')) {
            answers["Q" + counter] = 0;
            counter++;
        }

        else if ($('#Option1').is(':checked')) {
            answers["Q" + counter] = 1;
            counter++;
        }

        else if ($('#Option2').is(':checked')) {
            answers["Q" + counter] = 2;
            counter++;
        }

        else if ($('#Option3').is(':checked')) {
            answers["Q" + counter] = 3;
            counter++;
        }

        else {
            alert("Please make your selection before continuing!");
        }

        // this checks if there are any questions left, otherwise it goes to the result screen
        if (allQuestions[counter]) {
            qload(counter);
        }
        else {
            result();
        }
    });
}

welcome();

});
4

2 に答える 2

3

1) 文字列をインデックスとして使用して配列の要素を参照することはできません (answers["Q" + i])。配列インデックスとして数値を使用するか、配列の代わりにオブジェクトを使用する必要があります。

2) "checked" などの DOM プロパティを変更するために .attr() メソッドを使用しないでください。代わりに.prop()メソッドを使用してください。したがって、このスニペットを置き換える必要があります。

if (answers["Q" + i]) {
    $("#Option" + i).attr("checked","checked");
}

else {
    $("#Option" + i).removeAttr('checked');
}

次のように:

$("#Option" + i).prop("checked", Boolean(answers["Q" + i]));

3)ユーザーの回答の価値を得る方法は非常に面倒ですが、奇妙です。このコード:

    if ($('#Option0').is(':checked')) {
        answers["Q" + counter] = 0;
        counter++;
    }

    else if ($('#Option1').is(':checked')) {
        answers["Q" + counter] = 1;
        counter++;
    }

    else if ($('#Option2').is(':checked')) {
        answers["Q" + counter] = 2;
        counter++;
    }

    else if ($('#Option3').is(':checked')) {
        answers["Q" + counter] = 3;
        counter++;
    }

    else {
        alert("Please make your selection before continuing!");
    }

次のものに置き換えることができます。

var oEl = $('input:radio[name=radio]:checked');
if (oEl.length) {
    answers[counter] = parseInt(oEl.val());
    counter++;
}
else {
    alert("Please make your selection before continuing!");
}

また、ラジオ ボタンの html コードの次の修正が必要です。

<input type="radio" name="radio" id="Option0" value="0" />
<label for ="Option0">Option0</label>

さらに、その他のいくつかの変更...

したがって、コード全体の更新は次のとおりです。

$(document).ready(function () {
var allQuestions = [
    {question: "Who is Prime Minister of the United Kingdom?",
        choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
        correctAnswer: 0},
    {question: "Which color has the sky?",
        choices: ["Grey", "Black", "Blue", "Green"],
        correctAnswer: 2},
    {question: "What's on the chain?",
        choices: ["Monster", "Magician", "Bull", "Skull"],
        correctAnswer: 3}
];

var counter = 0; // Question No. currently processed
var answers = new Array(); // Array of the choices the player made

$('#back').click(function(){
    counter++;
    quiz();
});

// update Back button appearance
function updateBackBtn() {
    if (counter > 0)
        $("#back").show();
    else
        $("#back").hide();
}

// set current question
function qload(counter) {
    $("title").text("Question No ");
    $("#question").text(allQuestions[counter].question);
    updateBackBtn();
    for (var i = 0; i < allQuestions[counter].choices.length; i++) {
        $('label[for=Option' + i + ']').html(allQuestions[counter].choices[i]);

        $("#Option" + i).prop("checked", Boolean(answers[i]));
    }
};

// this is the result screen giving the final amount of points
function result() {
    $("title").text("Your Results");
        var points = 0; // Total points currently reached by the player
    for (var i = 0; i < allQuestions.length; i++) {
        if (allQuestions[i].correctAnswer == answers[i]) {
            points++;
        }
        $("#result").show().text("CONGRATULATIONS! You answered " + points + " out of " + allQuestions.length + " correct!");
        $(".qbox").hide();
        console.log(answers);

    }
}

function welcome() {
    // this is the welcome screen inviting to start the quizz
    $("title").text("Welcome to the JQuery QuizY");
    $(".qbox").hide();
    $("#result").append().html("Random");
    $("#result").append().html("<p id='start'>Start</p>");
    $("#start").on('click', function () {
        quiz();
    });
}

function quiz() {
    $("#start, #result").hide();
    $(".qbox").show();
    qload(counter);
    $("#next").on('click', function () {
        // get an input element containing selected option (answer)
        var oEl = $('input:radio[name=radio]:checked');
        // if such input element exists (any answer selected)
        if (oEl.length) {
            answers[counter] = parseInt(oEl.val());
            counter++;
        }
        else {
            alert("Please make your selection before continuing!");
        }

        // this checks if there are any questions left, otherwise it goes to the result screen
        if (counter < allQuestions.length) {
            qload(counter);
        }
        else {
            result();
        }
    });
}

welcome();

});
于 2013-07-21T15:58:07.363 に答える
1

私はコードを調べて、いくつかの変更を加えました。

以下の更新されたコードを確認してください。

$(document).ready(function () {
                var allQuestions = [
                    {question: "Who is Prime Minister of the United Kingdom?",
                        choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
                        correctAnswer: 0},
                    {question: "Which color has the sky?",
                        choices: ["Grey", "Black", "Blue", "Green"],
                        correctAnswer: 2},
                    {question: "What's on the chain?",
                        choices: ["Monster", "Magician", "Bull", "Skull"],
                        correctAnswer: 3}
                ];

                var counter = 0;     // Question No currently processed
                var points = 0;        // Total points currently reached by the player
                var answers = new Array(); // Array of the choices the player made  eg Q1:0

                // Back button in a function
                function back() {
                    if (counter > 0)          //Checks if there is at least one question already answered
                    {
                        $("#back").show();
                    }
                    else {
                        $("#back").hide();         //If there is no previous question existing the back button is deactivated
                    }
                }

                $('#back').click(function(){
                    counter = --counter;
                    quiz();//Executes quiz loading
                });

                function qload(counter) {
                    $("#title").html("Question No "+counter);
                    $("#question").text(allQuestions[counter].question);
                    back();
                    for (var i = 0; i < allQuestions[counter].choices.length; i++) {
                        $('label[for=Option' + i + ']').html(allQuestions[counter].choices[i]);
                        if (answers["Q" + counter] == i) {
                            $("#Option" + i).prop('checked',true);
                        }

                        else {
                            $("#Option" + i).removeAttr('checked');
                        }
                    }
                };

                //this is the result screen giving the final amount of points
                function result() {
                    $("#title").html("Your Results");
                    for (var i = 0; i < allQuestions.length; i++) {
                        if (allQuestions[i].correctAnswer == answers["Q" + i]) {
                            points++;
                        }


                        $("#result").show().text("CONGRATULATIONS! You answered " + points + " out of " + allQuestions.length + " correct!");
                        $(".qbox").hide();
                        console.log(answers);

                    }
                }

                function welcome() {
                    // this is the welcome screen inviting to start the quizz
                    $("title").html("Welcome to the JQuery QuizY");
                    $(".qbox").hide();
                    $("#result").append().html("Random");
                    $("#result").append().html("<p id='start'>Start</p>");
                    $("#start").on('click', function () {
                        quiz();
                    });
                }

                function quiz() {
                    $("#start, #result").hide();
                    $(".qbox").show();
                    qload(counter);
                }
                $("#next").click(function () {
                    // this checks that one question is selected before processing
                    if ($('#Option0').is(':checked')) {
                        answers["Q" + counter] = 0;
                        ++counter;
                    }

                    else if ($('#Option1').is(':checked')) {
                        answers["Q" + counter] = 1;
                        ++counter;
                    }

                    else if ($('#Option2').is(':checked')) {
                        answers["Q" + counter] = 2;
                        ++counter;
                    }

                    else if ($('#Option3').is(':checked')) {
                        answers["Q" + counter] = 3;
                        ++counter;
                    }

                    else {
                        alert("Please make your selection before continuing!");
                    }

                    // this checks if there are any questions left, otherwise it goes to the result screen
                    if (allQuestions[counter]) {
                        qload(counter);
                    }
                    else {
                        result();
                    }
                });

                welcome();

            });

上記の変更を行い、ローカルでテストしたところ、機能しました。

問題が発生した場合はお知らせください。

于 2013-07-22T08:00:54.207 に答える