在Javascript中匹配单选按钮选择与嵌套数组内容

时间:2014-06-02 13:12:07

标签: javascript arrays

更新6-25-2014

任何见解都将受到赞赏!

更新2014年6月21日

我试图制作全局的无线电变量,以便'answerFwd'函数中的'if block'可以与correctAnswer数组进行比较,但这不起作用!

更新2014年6月16日 已添加JS FIDDLE

我正在构建一个quiz并动态创建一个单选按钮数组,并希望将所选按钮与我在问题数组中建立的正确答案相匹配。

HTML

<div id="responses">
 <input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
 <div id="c0" class="choiceText">The Observers</div>
 <input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
 <div id="c1" class="choiceText">The Watchers </div>
 <input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
 <div id="c2" class="choiceText">The Sentinels</div>
 <input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
 <div id="c3" class="choiceText">The Oa</div>
</div>

的问题:

var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0 }, {
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3 },{},{} //other questions];


var item = allQuestions[0];

var currentQuestion = 0;

var playersScore = 0;

//创建按钮的功能

 function createRadioButtonFromArray(array) {
  var len = array.length;
  var responses = document.getElementById("responses"); 
  responses.innerHTML = '';
  for (var i = 0; i < len; i++) {
    radio = document.createElement("input"); //Updated 6-21-2014 removed 'var'
    radio.type = "radio";
    radio.name = "choices";
    radio.className = "radioButtons";
    radio.value = i;
    radio.id = "choice" + i;
    ar radioText = document.createElement("div");
    radioText.id = "c" + i;
    radioText.className = "choiceText";
    radioText.innerHTML = array[i];

    responses.appendChild(radio);
    responses.appendChild(radioText);
  }
}

function answerFwd() {
   var answerOutput = " ";
   var itemAnswers = allQuestions;

   var playerTally = 0; //Updated 6-9-2014
   var playerFeedback = " "; //Updated 6-9-2014
   var playerMessage = document.getElementById("playerMessage"); //Updated 6-9-2014

   if (currentAnswer <= itemAnswers.length) {
       currentAnswer++;
   }

   createRadioButtonFromArray(itemAnswers[currentQuestion].choices); 

*更新于6-9-2014我很难过;这不起作用但我鼓励我在页面上得到一个分数!我正确地比较了元素吗?更新于6-21-2014这颠倒了收益,我在屏幕上显示了计数*

   if (itemAnswers.correctAnswer === responses.id) { //Updated 6-21-2014
    playerTally += 1;
    playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
    playerMessage.innerHTML = playerFeedback;
   }

}

1 个答案:

答案 0 :(得分:0)

起初我尝试对此进行调试,但无法找到错误的来源。

我注意到的一件事是currentAnswer变量只被设置一次。 (宣布时)

使这个更清洁的另一件事是将每个问题的每个响应存储为问题对象的属性。

例如: {"question": "What is the registry of the Starship Reliant?","choices": ["NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],"correctAnswer": 1,"selectedAnswer": 0}


这是一个很好的例子,说明为什么你可能想要使用面向对象的编程。您可以保持全局命名空间的清洁,同时还可以更严格地控​​制变量。

我使用一些面向对象的原则将Quiz Code放在一起:

<强>的JavaScript

var Quiz = function(questions) {
    this.questions = questions;

    this.$template = {
        "header": document.querySelector(".question"),
        "options": document.querySelector(".question-choices")
    };

    this.init();
}

Quiz.prototype = {
    "init": function() {
        this.question = 0;

        this.generateQuestion();
        this.bindEvents();
    },
    //gets called when this.question == this.questions.length, calculates a score percentage and alerts it
    "score": function() {
        var correctCount = 0;

        this.questions.forEach(function(question){
            if ( (question.selectedAnswer || -1) === question.correctAnswer ) correctCount += 1
        })

        alert("Score: " + ((correctCount / this.questions.length) * 100) + "%")
    },
    //Gets called during initialization, and also after a nav button is pressed, loads the question and shows the choices
    "generateQuestion": function() {
        var question = this.questions[this.question];

        this.$template.header.innerHTML = question.question;
        this.$template.options.innerHTML = "";
        question.choices.forEach(this.createRadio.bind(this));
    },
    //Binds the previous, and next event handlers, to navigate through the questions
    "bindEvents": function() {
        var _this = this,
            $nextBtn = document.querySelector(".question-navigation--next"),
            $prevBtn = document.querySelector(".question-navigation--prev");

        $nextBtn.addEventListener("click", function(e) {
            //Go to the next question
            _this.question++;

            if ( _this.question == _this.questions.length ) {
                _this.score();
            } else {
                _this.generateQuestion();
            }
        });

        $prevBtn.addEventListener("click", function(e) {
            _this.question--;

            if ( _this.question <= 0 ) _this.question = 0

            _this.generateQuestion();
        });
    },
    //Create each individual radio button, is callback in a forEach loop
    "createRadio": function(choice, index) {
        var question = this.questions[this.question];

        var radio = document.createElement("input");
        radio.type = "radio";
        radio.name = "options";
        radio.id = "option-"+index;

        if ( question.selectedAnswer === index ) {
            radio.checked = true;
        }

        radio.addEventListener("click", function(e) {
            question.selectedAnswer = index;
        })

        var radioText = document.createElement("label");
        radioText.setAttribute("for", "option-"+index)
        radioText.innerHTML = choice;

        radioText.insertBefore(radio, radioText.firstChild);
        this.$template.options.appendChild(radioText);
    }
}

var q = new Quiz(allQuestions)