Bacchus
Bacchus

Reputation: 515

Add an event handler to an array

I want when the user clicks the "next" button to move to the next question. The problem here is when I click the button, it only show the first question. Where is the problem? I know 'return' returns the result to the function, but next time when I press the button, the iterator(i) is not i+1?

var changeQuestion = function() {
    for (var i = 0; i < allQuestions.length; i++) {
        var newNode = document.createTextNode(allQuestions[i].question);
        return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
    }
};

EventUtil.addHandler(next_button, 'click', changeQuestion);

Upvotes: 0

Views: 97

Answers (1)

Tanatos
Tanatos

Reputation: 1917

Try this :

var i = -1;
function changeQuestion() {
    i = (i < allQuestions.length) ? (i+1) : -1;
    var newNode = document.createTextNode(allQuestions[i].question);

    return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
}
EventUtil.addHandler(next_button, 'click', changeQuestion);

Upvotes: 1

Related Questions