请查看我为您创建的这个演示点击这里查看演示
更新的演示单击此处获取更新的演示
HTML 代码
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<br/>
<label data-bind="text: selectedChoice"></label>
Javascript代码
var CountryModel = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.countries = ko.observableArray([
new CountryModel({id: "1", name: "Russia"}),
new CountryModel({id: "2", name: "Qatar"})]);
};
ko.applyBindings(new viewModel());
开始更新
更新内容:
HTML 代码:
在事件 Click 上添加按钮它调用sendMe
返回 json 对象的函数selectedCountryId
<input type="button" data-bind="click: sendMe, enable: selectedChoice" Value="Click Me"/>
Javascript代码
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
END UPDATE
START UPDATE1
这是最后一条评论的更新,关于避免添加模型,在这种情况下让我们跳过CountryModel
因此,Javascript 代码将如下:
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.countries = ko.observableArray([
{id: "1", name: "Russia"},
{id: "2", name: "Qatar"}]);
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
};
ko.applyBindings(new viewModel());
END UPDATE1
希望对您有所帮助。
谢谢。