Question

Most of the action is in the function next. The other functions are provided for context. The global variable tally increments as it should when the right answer is selected. However the variable nr is not incremented and I can't figure out way it is not.

You can see that I commented out that the next function returned an object with tally and nr and assigned those values in the event listener. When I did it that way, it worked. But it should work the other way as well, right.

var nr = 0;
var tally = 0;

function onLoadEvent(nr) {
    //alert('onload');
    var quiz = document.getElementById('quiz');
    var question = allQuestions[nr];
    var next = quiz.lastElementChild;

    var qHeader = "<h2>" + question.question + "</h2>";
    var q = "";
    for(var i=0;i<question.choices.length;i++){
        q = q + '<p><label for="a' + i + '">' +
            '<input type="radio" id="a' + i + '" name="q" value="' +
            i + '">' + question.choices[i] + '</label></p>';
    }
    quiz.innerHTML = qHeader + q + next.outerHTML;
    //next = document.getElementById('next');
}

function getChecked(){
    var radios = document.getElementsByName('q');
    var radio;
    for(var i=0;i<radios.length;i++){
        if(radios[i].checked){
            radio = radios[i];
            break;
        }
    }
    return radio;
}

function next(nr){
    if (getChecked() !== undefined) {
        var answer = getChecked();
        if(answer.value == allQuestions[nr].correctAnswer){
            tally = tally + 1;
        }
        nr = nr + 1;
        if (nr>=allQuestions.length){
            alert("You got " + tally + " points!");
        } else {
            onLoadEvent(nr);
        }
    } else {
        alert('You need to check a radio button');
    }
    //return {nr: nr, tally: tally};
}

var form = document.getElementById('quiz');
form.addEventListener('click', function(event){
    if(event.target.id === 'next'){
        next(nr);
        //nr = obj.nr;
        //tally = obj.tally;
    } else if(event.target.id === 'prev'){}
}, false);

window.addEventListener('load', function(event){onLoadEvent(nr);}, false);
Était-ce utile?

La solution

You are accepting parameters with same name nr which is hiding global scope nr.

Solution to your problem is remove nr as parameter. So use function onLoadEvent() instead of function onLoadEvent(nr)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top