我只想显示当前的问题选项。我已将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