【发布时间】:2015-03-09 23:20:55
【问题描述】:
我有以下代码在特定索引处显示数组中的字符串。每次调用该函数并显示一个新字符串时,索引都会增加:
var questions = ["What is your name?","What is your favourite colour?","What is the air speed velocity of an unladen swallow?"];
var currentQuestionIndex = 0;
function showQuestion() {
if (currentQuestionIndex <= questions.length-1) {
var question = $('#question');
console.log(questions[currentQuestionIndex]);
question.text(questions[currentQuestionIndex]);
currentQuestionIndex = currentQuestionIndex+1;
questionTimer();
} else {
console.log("End question 1");
}
}
function questionTimer() {
setTimeout(function () {
showQuestion();
}, 3000);
}
showQuestion();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="question"></div>
这很好用,但是一旦我尝试淡出/淡出问题 div,代码将不再正常工作,并且显示索引 1 处的字符串而不是 0。谁能解释为什么?
非工作版本:
var questions = ["What is your name?","What is your favourite colour?","What is the air speed velocity of an unladen swallow?"];
var currentQuestionIndex = 0;
function showQuestion() {
if (currentQuestionIndex <= questions.length-1) {
var question = $('#question');
question.fadeOut(400, function () {
question.text(questions[currentQuestionIndex]);
question.fadeIn(400);
});
currentQuestionIndex = currentQuestionIndex+1;
questionTimer();
} else {
console.log("End question 1");
}
}
function questionTimer() {
setTimeout(function () {
showQuestion();
}, 3000);
}
showQuestion();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="question"></div>
【问题讨论】:
-
在淡出回调中移动
currentQuestionIndex = currentQuestionIndex+1; questionTimer();;)
标签: javascript jquery arrays settimeout