我對JSON中的多維數組有點新,而且我現在一直在用一些東西來敲打我的頭。讓我後下
JSON我的代碼:
{
"easy_questions": [
{
"q": "Question 1",
"a": [
{"option":"Answer 1", "correct": false},
{"option":"Answer 2", "correct":true},
{"option":"Answer 3", "correct":false},
{"option":"Answer 4", "correct": false}
],
"image": false,
"source": "dsa"
},
{
"q": "Question 2",
"a": [
{"option":"Answer 1", "correct": false},
{"option":"Answer 2", "correct":true},
{"option":"Answer 3", "correct":false},
{"option":"Answer 4", "correct": false}
],
"image": false,
"source": false
}, // this goes on for about 7 more questions...
],
"step2_easy": [
{
"q": "Question 1",
"a": [
{"option":"Answer 1", "correct": false},
{"option":"Answer 2", "correct":true},
{"option":"Answer 3", "correct":false},
{"option":"Answer 4", "correct": false}
],
"image": false,
"source": false
},
{
"q": "Question 2",
"a": [
{"option":"Answer 1", "correct": false},
{"option":"Answer 2", "correct":true},
{"option":"Answer 3", "correct":false},
{"option":"Answer 4", "correct": false}
],
"image": false,
"source": false
}, //goes on again
而且我的JavaScript
function quizFun() {
var questions = [];
var answers = [];
var quiz = "url.to/questions.json";
$.getJSON(quiz, function(data) {
lvl_1(data);
function lvl_1(data) {
var easy = data.easy_questions;
function shuffle(array) {
var counter = array.length, temp, index;
// While there are elements in the array
while (counter--) {
// Pick a random index
index = (Math.random() * counter) | 0;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
var randoms = shuffle(easy.slice(0));
randoms.length = 3;
jQuery.each(randoms, function(i, val) {
var question = val.q,
sourse = val.source;
img = val.image;
answ = val.a;
option = null;
correct = null;
$.each(answ,function(option, correct) {
option = this.option;
correct = this.correct;
answers = '<span data-true="'+correct+'">'+option+'</span>';
return answers;
});
if(!img) {
html_strucutre = question + answers;
} else {
html_strucutre = question + '<img src="'+img+'" width="300">' + answers;
}
$('body').append(html_strucutre+'<br>');
});
}
});
我知道這是不是最好的,但我想這一個與梳理小步驟。
首先,我需要得到3個隨機問題'easy_questions',以及相應的答案(true或false)。一旦我經歷了其中的3個,我會跳到下一個等等。
我確實設法得到問題甚至答案,但每當我試圖退出$.each(answ,function(option, correct) {..}
時,它只會爲每個問題返回一個答案,並且總是最後一個答案。
這裏有什麼嚴重錯誤?
您需要連接的答案是什麼樣子。 '+ +''+ +'+''+'+'+''' –
不需要在其他函數和回調中嵌套像'shuffle'這樣的實用函數聲明 – charlietfl