我正在用 Knockoutjs 设计一个测验。我想一次只显示一个问题。我在考虑一个全局计数变量,每次回答一个问题时都会加 1。但是我似乎无法找到一种方法来得到一个问题。我将如何最好地解决这个问题?我是 Knockoutjs 的新手。我尝试了 questions()[number] 但这似乎不起作用。
谢谢
JS
$(document).ready(function(){
function Answer(data) {
this.answer = ko.observable(data.answer);
this.correct = ko.observable(data.correct);
}
function Question(data){
this.id = ko.observable(data.id);
this.question = ko.observable(data.question);
this.answers = ko.observableArray([]);
var mappedAnswers = $.map(data.answers, function(item) {return new Answer(item) });
this.answers(mappedAnswers);
}
function AnswerViewModel(){
// Data
var self = this;
self.questions = ko.observableArray([]);
self.checkAnswer = function(item, event){
if (item.juist() == true){
$(event.currentTarget).css("background", "green");
}else{
$(event.currentTarget).css("background", "red");
}
}
$.getJSON("../res/json/quiz.json", function(allData) {
var mappedQuestions = $.map(allData.questions, function(item) {return new Question(item) });
self.questions(mappedQuestions);
});
}
ko.applyBindings(AnswerViewModel());
});
HTML
<h3 data-bind="questions()[1].question"></h3>
<ul class="list-container" data-bind="foreach: questions()[1].answers">
<li class="list-item">
<a class="list-item-content" href="#" data-bind="text: answer, click:checkAnswer"></a>
</li>
</ul>
<button>Next question</button>
JSON
{
"questions" :
[
{
"id": 1,
"question": "This is the first question",
"answers" :
[
{"answer": "q1a1", "correct": false},
{"answer": "q1a2", "correct": false} ,
{"answer": "q1a3", "correct": true},
{"answer": "q1a4", "correct": false}
]
},
{
"id": 2,
"question": "This is the 2nd question",
"answers" :
[
{"answer": "q2a1", "correct": false},
{"answer": "q2a2", "correct": false} ,
{"answer": "q2a3", "correct": false},
{"answer": "q2a4", "correct": true}
]
}
]
}