选项
使用此绑定为选择项构建选项
<select data-bind="options: gasGiants"></select>
<script type="text/javascript">
var viewModel = {
gasGiants: ko.observableArray(['Jupiter', 'Saturn', 'Neptune', 'Uranus'])
};
</script>
你还可以使用数组中的属性在列表中显示并保存在 viewModel 中:optionsText
启用自定义显示文本
optionsValue
设置相应 <option>
的 value 属性
value
将所选选项的值存储到 viewModel 的 observable 中
<select data-bind="options: gasGiants, optionsText:'name', optionsValue:'id', value:selectedPlanetId"></select>
<script type="text/javascript">
var viewModel = {
selectedPlanetId: ko.observable(),
gasGiants: ko.observableArray([{name:'Jupiter', id:'0'},
{name:'Saturn', id:'1'},
{name:'Neptune', id:'2'},
{name:'Uranus', id:'3'}])
};
</script>
要存储多选列表的结果,可以将选项绑定与 selectedOptions
绑定结合使用。
<select data-bind="options: gasGiants, selectedOptions: chosenGasGiants" multiple="true"></select>
<script type="text/javascript">
var viewModel = {
gasGiants: ko.observableArray(['Jupiter', 'Saturn', 'Neptune', 'Uranus'])
chosenGasGiants: ko.observableArray(['Jupiter','Saturn']) // Initial selection
}; </script>