Ani*_*pta 6 knockout-2.0 knockout.js
我想获得所选的选项对象
<select data-bind="options: availableCountries,
value: selectedCountry, event: { select: onSelect}"></select>
<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
onSelect: function(){
console.log(viewModel.selectedCountry)
// it is showing just an country name and what i what is whole object
// e.g. { "UK", 65000000 } // that is selected option in selected box
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
Art*_*kov 16
您不必将select事件添加到控件.更有效的方式是订阅selectedCountry更改:
viewModel.selectedCountry.subscribe(function (data) {
console.log(data)
});
Run Code Online (Sandbox Code Playgroud)
如果您不希望默认选择任何国家/地区,则必须将optionsCaption绑定添加到data-bind:
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Select...'"></select>
Run Code Online (Sandbox Code Playgroud)
这是工作小提琴:http://jsfiddle.net/vyshniakov/tuMta/1/
| 归档时间: |
|
| 查看次数: |
11089 次 |
| 最近记录: |