我无法弄清楚使用 JavaScript 对象和 KnockOutJS 选择选项的正确语法。我直接从http://knockoutjs.com/documentation/options-binding.html中获取了下面的示例,示例 3。
<p>
Your country:
<select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
<script type="text/javascript">
// Constructor for an object with two properties
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() // Nothing selected by default
};
</script>
selectedCountry 没有选择任何内容,如备注中所述。假设我想默认选择美国。
我试过这个:
selectedCountry : ko.observable([availableCountries()[1]])
我试过这个:
selectedCountry : ko.observable([new Country("USA", 320000000)])
我可能只是遗漏了一些非常明显的东西(我正在与极度感冒作斗争)......有人可以指出我的疏忽或误解吗?