我只想顯示當前的問題選項。我已將ViewModel中的currentQuestion設置爲數組中的第一個元素。 但它是未定義的。 我安裝了淘汰賽上下文chrome插件,並且所有其他變量似乎設置正確。我不知道爲什麼currentQuestion具有未定義的值。 感謝爲什麼currentQuestion未定義?
<div id="quiz-container">
<form action="">
<div data-bind="with: currentQuestion">
<h3 data-bind="text: question"></h3>
<div data-bind="foreach: choices">
<input type="radio" data-bind="checkedValue: $data, checked: $parent.selectedAnswer" />
<span data-bind="text: $data">choice</span>
</div>
<div>
<button data-bind="click: $parent.previousQuestion">Previous</button>
<button data-bind="click: $parent.nextQuestion">Next</button>
</div>
</div>
<div><input type="submit"/></div>
</form>
</div>
<script src="js/jQuery.js"></script>
function Question(data) {
var self = this;
self.question = data.question;
self.choices = ko.observableArray([]);
data.choices.forEach(function (c) {
self.choices.push(c);
});
self.answer = data.answer;
};
function QuizViewModel() {
var self = this;
self.questionList = ko.observableArray([]);
// Load initial state from server, convert it to Question instances, then populate self.questions
$.getJSON("js/questions.json", function (allData) {
var mappedQuestions = $.map(allData, function (item) {
return new Question(item)
});
self.questionList(mappedQuestions);
});
self.currentQuestion = ko.observable(self.questionList()[0]);
this.previousQuestion = function() {
var index = self.questionList().indexOf(self.currentQuestion);
self.currentQuestion(self.questionList()[index - 1]);
};
this.nextQuestion = function() {
var index = self.questionList().indexOf(self.currentQuestion);
self.currentQuestion(self.questionList()[index + 1]);
};
};
ko.applyBindings(new QuizViewModel());
檢查self.questionList()[index-1]是否有正確的值? – 2015-03-13 11:50:29