Knockout select 列表 - 指定一个默认值
Knockout select list - specify a default value
将数据绑定到包含对象的 select 列表时,如何指定默认值?
我正在尝试以下方式:
var Country = function(name, population) {
this.countryName = name;
this.countryPopulation = population;
};
var viewModel = {
availableCountries: ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]),
selectedCountry: ko.observable(new Country("USA", 320000000))
};
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Choose...'"></select>
想法是 availableCountries
将包含一个 Country
对象数组,selected 对象保存在 selectedCountry
observable 中。
除了在列表中预 select 值外,一切都按预期工作。
我预计它不起作用,因为它们实际上是不同的对象引用。让这个工作的最干净和最简单的方法是什么?我希望美国国家/地区默认设置为 select。
这里有一个fiddle来说明问题:
https://jsfiddle.net/85crLcy2/
您可以拆分选项数组,然后将 selectedCountry 设置为美国选项:
var choices = [
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
];
var viewModel = {
availableCountries: ko.observableArray(choices),
selectedCountry: ko.observable(choices[1])
};
将数据绑定到包含对象的 select 列表时,如何指定默认值?
我正在尝试以下方式:
var Country = function(name, population) {
this.countryName = name;
this.countryPopulation = population;
};
var viewModel = {
availableCountries: ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]),
selectedCountry: ko.observable(new Country("USA", 320000000))
};
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Choose...'"></select>
想法是 availableCountries
将包含一个 Country
对象数组,selected 对象保存在 selectedCountry
observable 中。
除了在列表中预 select 值外,一切都按预期工作。
我预计它不起作用,因为它们实际上是不同的对象引用。让这个工作的最干净和最简单的方法是什么?我希望美国国家/地区默认设置为 select。
这里有一个fiddle来说明问题: https://jsfiddle.net/85crLcy2/
您可以拆分选项数组,然后将 selectedCountry 设置为美国选项:
var choices = [
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
];
var viewModel = {
availableCountries: ko.observableArray(choices),
selectedCountry: ko.observable(choices[1])
};