使用此绑定为选定项目构建选项
<select data-bind="options: gasGiants"></select> <script type="text/javascript"> var viewModel = { gasGiants: ko.observableArray(['Jupiter', 'Saturn', 'Neptune', 'Uranus']) }; </script>
您还可以使用数组内的属性在列表中显示和在viewModel中保存:optionsText启用自定义显示文本
optionsValue 设置对应的value属性 <option>
value 将所选选项的值存储到viewModel的可观察对象中
<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']) // 初始选择 }; </script>