覆盖全局变量并返回另一个函数javascript

时间:2014-04-16 16:36:18

标签: javascript global-variables return-value

如何在createQuestion()中更新currentQuestion 每次单击该按钮时,currentQuestion将更新* 1,但在createQuestion()函数中,currentQuestion的值仍为0.

var currenQuestion = 0;

function nxtQuestion() {
    var button = document.getElementById('nextQuestion');
    document.getElementById('genralCulture').addEventListener('click', function (event) {
        if (event.target == button) {
            currenQuestion += 1;
            //createQuestion();
            event.preventDefault();
        }
    }, false);
}

function createQuestion() {
    var question = document.getElementById('theQuestion');
    if (currenQuestion < allQuestions.length) {
        nxtQuestion();
        question.innerHTML = allQuestions[currenQuestion].question;
    } else {
        question.innerHTML = "Your score is "
    }
}

换句话说,当我点击按钮时,问题不是更新,但事件处理程序正常工作

1 个答案:

答案 0 :(得分:0)

试试这个

var currenQuestion = 0;

function nxtQuestion() {
var button = document.getElementById('nextQuestion');
document.getElementById('genralCulture').addEventListener('click', function (event) {
    if (event.target == button) {
        currenQuestion += 1;
        //createQuestion();
        event.preventDefault();
    }
}, false);
}

function createQuestion() {
 currenQuestion += 1;
var question = document.getElementById('theQuestion');
if (currenQuestion < allQuestions.length) {
    nxtQuestion();
    question.innerHTML = allQuestions[currenQuestion].question;
} else {
    question.innerHTML = "Your score is "
}
}