Javascript测验-获取选定的单选按钮值并比较以得到正确答案

时间:2019-02-11 17:15:44

标签: javascript html arrays foreach radio-button

我对Web开发非常陌生,这是我的第一个项目。我正在尝试使用数组来创建测验,以显示问题,选择和答案。我已经成功地在网页上显示了问题和选择。但是我仍然无法显示用户选择或获取所选的单选按钮。我必须这样做,以便可以在本测验中显示分数。

HTML:

<!DOCTYPE Html>
<html>
    <head>
    </head>

    <body>
        <div id="quiz"></div>
        <button id="button">Done!</button>
        <script src="scripts.js"></script>
    </body>
</html>

Javascript:

var myQuestions = [
['1. Which sentence uses "famish" correctly?', "After the straight exam, I 
felt too exhausted and famished to eat my favourite foods.", "I could eat a 
horse, I am famish now.", "I famished my stomach next time you treat me to a 
meal out.", "I will bring lots of pizza, that's a famish.", "a"],
["2. Priscila _______ rather not invest her savings in the stock market.", 
"must", "has to", "could", "would", "d"],
["3. Did you have any problem ______ our house?", "search", "to search", 
"searching", "for searching", "c"],

/*********************************************************************/

var quiz_id = document.getElementById('quiz');
var submitButton = document.getElementById("button");

/*********************************************************************/

myQuestions.forEach(function(myQuestions){

quiz_id.innerHTML += `
    <div>${myQuestions[0]} <br></div>
    <form>
        <label>
            <input class="answers" type="radio" name="choices" 
             value="a">${myQuestions[1]}<br/>
             <input class="answers" type="radio" name="choices" 
             value="b">${myQuestions[2]}<br/>
            <input class="answers" type="radio" name="choices" 
            value="c">${myQuestions[3]}<br/>
            <input class="answers" type="radio" name="choices" 
            value="d">${myQuestions[4]}<br/>
            </label>
    </form>
`;
});

/*********************************************************************/

function showResults(){

//1. set the total score
var total = 0;

//2. show the correct answer
myQuestions.forEach(function(myQuestions, index){
    var correctAnswer = myQuestions[5];
    quiz_id.innerHTML += `<div>correct answer for number ${index} : 
    ${correctAnswer}</div>`;
});

//3. show the user their answer
var choice = document.getElementsByName('choices');
var userChoice;
for(var i = 0; i < choice.length; i++){
    if(choice[i].checked){
        userChoice = choice[i].value;
    }
    quiz_id.innerHTML += `${userChoice}`;
}

//4. if the user choice matches the correct answer add a score to total 
variable
if(userChoice === correctAnswer){
    total++;
}
//5. display the scores
quiz_id.innerHTML = `<div>You have scored a total of ${total}</div>`;

}

/*********************************************************************/

submitButton.addEventListener("click", showResults);

在函数showResults()

我遇到3号和4号的麻烦。

1 个答案:

答案 0 :(得分:0)

我宁愿使用对象,而不是使用数组来存储您以后应使用的数据(例如数据库)(因为索引使事情变得更容易)

希望代码能对您有所帮助。

var myQuestions = {
    q1: { // unique id for every question
        question: 'Which sentence uses "famish" correctly?',
        correctAnswer: 'After the straight exam, I felt too exhausted and famished to eat my favourite foods.',
        fakeAnswers: [
            'I could eat a horse, I am famish now.',
            'I famished my stomach next time you treat me to a meal out.',
            'I will bring lots of pizza, that\'s a famish.',
        ],
    },
    q2: {
        question: 'Priscila _______ rather not invest her savings in the stock market.',
        correctAnswer: 'would',
        fakeAnswers: ['must', 'has to', 'could'],
    },
    q3: {
        question: 'Did you have any problem ______ our house?',
        correctAnswer: 'searching',
        fakeAnswers: ['search', 'to search', 'for searching'],
    },
};

/*********************************************************************/

var quiz_id = document.getElementById('quiz');
var submitButton = document.getElementById('button');
var userAnswers = {}; // store the selected answers in this object, indexed by question id

/*********************************************************************/

var aQuestion;
Object.keys(myQuestions).forEach((questionId, arrayIndex) => {
    aQuestion = myQuestions[questionId];
    var questionContainer = document.createElement('div');
    var questionLabel = document.createElement('label');
    var optionContainer = document.createElement('section');
    var answers = [aQuestion.correctAnswer].concat(aQuestion.fakeAnswers);

    shuffleArray(answers);
    answers.forEach((answer) => {
        var radioButton = generateRadioButton(questionId, answer);
        optionContainer.appendChild(radioButton);
    });

    questionLabel.innerText = `${arrayIndex + 1}. ${aQuestion.question}\n`;

    questionContainer.appendChild(questionLabel);
    questionContainer.appendChild(optionContainer);
    quiz_id.appendChild(questionContainer);
});

/*********************************************************************/

function showResults(params) {
    // Do your things
    console.log(userAnswers);

    // check a specific question (by question id)
    var qId = 'q2';
    if (userAnswers[qId] == myQuestions[qId].correctAnswer) {
        console.log(`The answer [${userAnswers[qId]}] is correct for the question: "${myQuestions[qId].question}"`);
    }
}

/*********************************************************************/

submitButton.addEventListener('click', showResults);

/*********************************************************************/

function generateRadioButton(groupId, value) {
    var container = document.createElement('div');
    var label = document.createElement('label');
    var radioButton = document.createElement('input');

    radioButton.className = 'answers';
    radioButton.type = 'radio';
    radioButton.id = value;
    radioButton.value = value;
    radioButton.name = groupId;
    radioButton.addEventListener('input', (event) => {
        userAnswers[groupId] = event.currentTarget.value;
    });

    label.innerText = value;
    label.htmlFor = value;

    container.appendChild(radioButton);
    container.appendChild(label);

    return container;
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}