Tôi đang thiết kế một bài kiểm tra với Knockoutjs. Tôi chỉ muốn hiển thị một câu hỏi tại một thời điểm. Tôi đã suy nghĩ về một var đếm toàn cầu được thêm vào bởi mỗi lần một câu hỏi được trả lời. Tuy nhiên tôi dường như không thể tìm ra cách để chỉ có một câu hỏi vào lúc đó. Làm cách nào để tôi tiếp cận tốt nhất điều này? Tôi mới đến Knockoutjs. Tôi đã thử các câu hỏi() [số] nhưng điều đó dường như không hiệu quả.Nhận đối tượng từ observableArray theo chỉ mục
Cảm ơn
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}
]
}
]
}
Cảm ơn bạn đã trả lời! Tôi thực sự đánh giá cao bạn đã dành thời gian để giải thích điều này. Tôi đã thử nó nhưng không có gì đáng buồn được hiển thị. Có điều gì khác tôi đang làm sai? – MrJM
Tôi đã thực hiện một vài lỗi trong mã của mình, đó là 'self.questions()', không phải câu hỏi, và trong câu hỏi tiếp theo bạn cần một parseInt như 'self.currentQuestionId (parseInt (currentQuestionId, 10) + 1);'; đây là codepen - http://codepen.io/jjperezaguinaga/full/jIytF – jjperezaguinaga
Awsome nó hoạt động, cảm ơn rất nhiều! – MrJM