向数组添加事件处理程序

Add an event handler to an array

本文关键字:程序 事件处理 添加 数组      更新时间:2023-09-26

我希望当用户点击"next"按钮时移动到下一个问题。这里的问题是,当我点击按钮,它只显示第一个问题。问题在哪里?我知道'return'将结果返回给函数,但下次当我按下按钮时,迭代器(I)不是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);

试试这个:

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);