我正在使用以下型号加载3个选择:
var viewModel = function(){
var self = this;
self.makes = [
{id: 1, name: 'Northwoods Prestige'},
{id:2, name: 'Forest Bay'},
{id:3, name: 'Timberland'}
];
self.types = [
{id: 1, make:1, name:'Special Reserve 138', patterns:['11.jpg','12.jpg']},
{id: 2, make:1, name:'Special Reserve II', patterns:['13.jpg','14.jpg']},
{id: 3, make:2, name:'TF 138', patterns:['15.jpg','16.jpg']},
{id: 4, make:2, name:'TF II', patterns:['17.jpg','18.jpg']},
{id: 5, make:3, name:'RP 25', patterns:['19.jpg','20.jpg']},
{id: 6, make:3, name:'LP 25', patterns:['21.jpg','22.jpg']}
];
self.models = [
{id:1, make:1,type: 1, name: 'Single Door'},
{id: 2, make:1,type: 1, name: 'Double Door'},
{id: 3, make:1,type: 2, name: 'Focus'},
{id: 5, make:2,type: 3, name: 'Q5'},
{id: 6, make:2,type: 3, name: 'Q7'},
{id: 7, make:2,type: 4, name: 'A3'},
{id: 8, make:2,type: 4, name: 'A4'},
{id: 9, make:2,type: 3, name: 'A6'}
];
self.selectedMake = ko.observable();
self.selectedType = ko.observable();
self.selectedModel = ko.observable();
self.carTypes = ko.computed(function(){
return ko.utils.arrayFilter(self.types, function(item){
return item.make === self.selectedMake();
});
});
self.carModels = ko.computed(function(){
return ko.utils.arrayFilter(self.models, function(item){
return item.make === self.selectedMake() && item.type === self.selectedType();
});
});
};
var model = new viewModel();
ko.applyBindings(model);
HTML:
<div>
<select id="make" data-bind="options: makes, value: selectedMake, optionsText : 'name', optionsValue : 'id'"></select><br/>
<select id="type" data-bind="options: carTypes, value: selectedType, optionsText : 'name', optionsValue : 'id'"></select><br/>
<select id="model" data-bind="options: carModels, value:selectedModel, optionsText: 'name', optionsValue : 'id'"></select>
</div>
<div>
<div data-bind="foreach: { data: carTypes, as: 'x' }">
<div data-bind="text: x.patterns"></div>
</div>
</div>
每当我更改select id =“make”模型更改(foreach)时,每当我更改select id =“type”中的值而不是第一个时,我都会尝试实现此目的。有帮助吗?谢谢
答案 0 :(得分:0)
我将optionsCaption
添加到类型选择器中,因此默认情况下不会选择一个。你可能不想要那个,我说不出来。
<select id="type" data-bind="optionsCaption:'Select...', options: carTypes, value: selectedType, optionsText : 'name', optionsValue : 'id'"></select>
我创建了一个新的计算器,以便从carTypes
获取与selectedType
匹配的条目:
self.matchingTypes = ko.computed(function () {
var selectedType = self.selectedType();
return ko.utils.arrayFilter(self.carTypes(), function (item) {
return item.id === selectedType;
});
});
我用它作为foreach:
<div data-bind="foreach: { data: matchingTypes, as: 'x' }">
<div data-bind="text: x.patterns"></div>
</div>
现在只显示与selectedType关联的模式。
要为图案添加图像而不是文本,例如:
<div data-bind="foreach: { data: matchingTypes, as: 'x' }">
<div data-bind="foreach: x.patterns">
<img data-bind="attr:{src:$data}" />
</div>
</div>