使用Javascript进行测验。从对象获取数组值。

时间:2014-11-13 08:55:21

标签: javascript html

我试图用Javascript创建一个简单的测验。我正在努力掌握如何从对象迭代数组值的概念。我最终想要显示一个单选按钮,其值作为答案的选择。如果有人能指出我正确的方向,我会非常感激。

小提琴:http://jsfiddle.net/Renay/eprxgxhu/

这是我的代码:

HTML     

        <h1> General Knowledge Quiz </h1> 

        <h2 id='questionTitle'> </h2>
        <ul id ='selectionList'> </ul>
        <p> Click the next button to go to the next question! </p>

        <button type="button" id = nextButton> Next </button>
    </div>  

Javascript

var allQuestions = [{
    question: 'What is the capital city of Australia?',
    choices: ['Sydney', 'Melbourne', 'Canberra', 'London'],
    correctAnswer: 2
},
{
    question: 'Who won the 2014 FIFA World Cup?',
    choices: ['Brazil', 'England', 'Germany', 'Spain'],
    correctAnswer: 2
},
{
    question: 'What book series is authored by J.K Rowling?',
    choices: ['Game of Thrones', 'Hunger Games', 'Twilight', 'Harry Potter'],
    correctAnswer: 3
},
{   
    question: 'The Eiffel Tower is located in which following country?',
    choices: ['Italy', 'France', 'Iceland', 'Mexico'],
    correctAnswer: 1
}];

//Reference to tags
var questionTitle = document.getElementById('questionTitle');
var selectionList = document.getElementById('selectionList');
var nextButton = document.getElementById('nextButton');

//Initiating some variables
var i = 0;
var length1 = allQuestions.length;
var correctAnswer = 0;

function populateQuestion() {}

2 个答案:

答案 0 :(得分:2)

首先将点击事件附加到下一个按钮,并使用计数器调用 populateQuestion()来遍历 allQuestions数组并使用 i 作为计数器变量。

nextButton.onclick = function() {
    /*itterate through questions*/    
    if(i>allQuestions.length -1){/*go to first when reached last*/
       i=0;       
    }    
    populateQuestion(i);
    i++;
};

通过 allQuestions数组迭代问题标题和选项:

function populateQuestion(qNum) {
    var individualQuestion = allQuestions[i];
    questionTitle.innerText = individualQuestion.question;

    selectionList.innerHTML = ""; //reset choices list
    for(key in individualQuestion.choices){
        var radioBtnName = "question"+i+"_choice";
        var choiceText = individualQuestion.choices[key];
        selectionList.appendChild(createLi(radioBtnName,choiceText));
    }
}

将动态li和单选按钮创建功能写为:

function createLi(name, choiceText) {
        var e = document.createElement('li');
        var radioHtml = '<input type="radio" name="' + name + '"';    
        radioHtml += '/>';
        radioHtml += choiceText;        
        e.innerHTML = radioHtml;        
        return e;
    }

refer to this fiddle

答案 1 :(得分:0)

您需要将onClick event与按钮相关联,才能调用JavaScript的相关部分。完成示例here

另一方面,使用JavaScript进行测验可能不是一个好主意,因为可以使用view-source查看答案。我建议使用PHP从数据库中获取结果。

相关问题