html
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<br/>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<input type="button" data-bind="click: sendMe, enable: selectedChoice" Value="Click Me"/>
KnockoutJS
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"})]);
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
};
ko.applyBindings(new viewModel());
我有两个问题:
答案 0 :(得分:0)
在视图模型中只需要2个独立的可观察对象即可存储每个列表的选定值;
这里selectedChoice1
和selectedChoice2
。
请参见下面的可运行示例。
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.selectedChoice1 = ko.observable();
self.selectedChoice2 = ko.observable();
self.countries = ko.observableArray([
new CountryModel({id: "1", name: "Russia"}),
new CountryModel({id: "2", name: "Qatar"})]
);
self.sendMe = function(){
alert(ko.toJSON({
"selectedCountryId1": this.selectedChoice1(),
"selectedCountryId2": this.selectedChoice2()
}));
};
};
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice1, optionsCaption: 'Choose..'"></select>
<br/>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice2, optionsCaption: 'Choose..'"></select>
<input type="button" data-bind="click: sendMe, enable: (selectedChoice1() && selectedChoice2())" Value="Click Me"/>