我正在做一個測驗來學習javascript(jquery),我已經走過了。之前,我只是用一個對象來存儲所有的問題。我「字符串化」該對象JSON格式,我使用此代碼檢索:如何從json文件測驗數據
var question;
$.getJSON('package.json', function(data) {
$.each(data, function(key, value){
question = value[currentQuestion].question;
var choices = value[currentQuestion].choices;
var correctAnswer = value[currentQuestion].correctAnswer;
var indexAnswer = value[currentQuestion].choices[correctAnswer];
});
});
的問題是,我不能使用全局變量的問題在每個方法分配給全球「範圍「(它說未定義)。 JSON通常用於將所有信息直接添加到dom中,但我依賴於當前問題編號,這使得我非常困惑。
之前我用這個代碼:
$questions.each(function (index) {
var choices = allQuestions[currentQuestion].choices[index];
$(this).next().text(choices);
});
在我使用動態currentQuestion數靜態加入每一個問題。
我有點失去了最佳的策略是爲這次測驗我想要的答案,以動態添加(我不希望這在我的HTML了。
<input name="group1" value="answer1" type="radio"/><span></span><br>
<input name="group1" value="answer2" type="radio"/><span></span><br>
<input name="group1" value="answer3" type="radio"/><span></span><br>
<input name="group1" value="answer4" type="radio"/><span></span><br>.
我不想讓你爲我編寫它,我只是想要一些指針/提示,我需要做什麼這項工作主要的問題是我如何使用JSON和jQuery的方式,它動態地將問題添加到測驗中