我正在使用Knockout 3.2,并且尝试显示具有某些选定值的多选下拉列表,但未选择这些值。问题在于KO没有填充选项的'value'属性:
<select data-bind="options: availableCountries, selectedOptions: chosenCountries, optionsText: 'name'" size="5" multiple="true">
<option value="">France</option>
<option value="">Germany</option>
<option value="">Spain</option>
</select>
虚拟机:
var viewModel = {
availableCountries : ko.observableArray([{name:'France'}, {name:'Germany'}, {name:'Spain'}]),
chosenCountries : ko.observableArray(['Germany'])
};
如果我将
availableCountries
而不是对象转换为简单的字符串数组,则可以使用。You can see a live sample here
最佳答案
var viewModel = {
availableCountries : ko.observableArray([{name:'France'}, {name:'Germany'}, {name:'Spain'}]),
chosenCountries : ko.observableArray(['Germany'])
};
['Germany']
不是{name: 'Germany'}
!而且,如果您编写
chosenCountries : ko.observableArray([{name: 'Germany'}])
,则会导致两个不同的对象,它们具有相同的属性name
和值'Germany'
。var viewModel = (function() {
var self = {};
self.availableCountries = ko.observableArray([{name:'France'}, {name:'Germany'}, {name:'Spain'}]);
self.chosenCountries = ko.observableArray([self.availableCountries()[1]]);
return self;
})();
ko.applyBindings(viewModel);
我将viewModel更改为一个可理解的函数,该函数返回viewModel。
(函数(){...})()
http://jsbin.com/monasijufaya/1/edit?html,js,output