$(document).ready(function() {
allQuestions
是对象数组,它的作用是为我的应用程序提供问题(question
),答案(choices
)和正确的响应(correctAnswer
)。
var allQuestions = [{question: "If you were a super hero what powers would you have?",
choices: ["a", "b", "c", "d"],
correctAnswer:0},
{question: "Do you have a cherished childhood teddybear?",
choices: ["e", "f", "g", "j"],
correctAnswer:0},
{question: "Whats your favourite non-alcoholic drink?",
choices: ["i", "j", "k", "l"],
correctAnswer:0},
{question: "Are you religious?",
choices: ["m", "n", "o", "p"],
correctAnswer:0}];
接下来,一旦我的按钮,与#next
id被点击,段落id #question
应该改变他的文本与下一个问题从allQuestions
数组。
实际结果?当我单击next按钮时,该函数遍历所有问题,并且只显示最后一个问题。
我试图使用stackoverflow的解决方案,设置var hasLooped
但不起作用。
$('#next').click(function(){
//var hasLooped = false;
$.each(allQuestions, function(key){
// if(!hasLooped) {
$('#question').text(allQuestions[key].question);
// }
// hasLooped = true;
})
})
});
将问题的索引保存在一个变量中,并在点击#next
时增加该索引
写这个:
$(function () {
var count = 0,
len = allQuestions.length;
$('#next').click(function () {
if (count < len - 1) {
count++;
$('#question').text(allQuestions[count].question);
} else {
$(this).remove();
});
});
fiddle
您需要将当前问题存储在外部某个地方并引用它,而不是传递给每个函数的键,因为它将始终循环遍历所有,您将看到最后一个。
var intNum = 1;
$('#next').click(function(){
$('#question').text(allQuestions[intNum].question);
intNum++;
});
var clickCount = 0;
$('#next').click(function(){
$('#question').text(allQuestions[clickCount].question);
clickCount=(clickCount+1>9)?0:clickCount+1;
});
如果你不喜欢全局变量,你可以试试这个:
$('#next').click(function(){
var counter = parseInt($("#next").attr("counter"));
if (counter>=allQuestions.length){
alert("No more questions!");
return;
}
$('#question').text(allQuestions[counter].question);
$("#next").attr("counter",counter+1);
});
DEMO