我有2个下拉菜单。当我从一个下拉列表中选择值时,它将根据所选内容在另一个下拉列表中加载值。
这是我的HTML代码
<select data-bind="options: filters, value: filter"></select>
<select data-bind="options: filteredItems, optionsText: 'name'"></select>
这是我的淘汰代码
var ViewModel = function(data) {
var self = this;
self.filters = ko.observableArray(data.filters);
self.filter = ko.observable('');
self.items = ko.observableArray(data.items);
self.filteredItems = ko.computed(function() {
var filter = self.filter();
if (!filter || filter == "None") {
return self.items.slice(0, 6);
} else {
return self.items.slice(2);
}
});
};
var initialData = {
filters: ["None", "Old", "New", "Super"],
items: [{ name: "Corvette", type: "Old"},
{ name: "Charger", type: "Old"},
{ name: "Prius", type: "New"},
{ name: "Magnum", type: "New"},
{ name: "McLaren", type: "Super"},
{ name: "Saleen", type: "Super"}]
ko.applyBindings(new ViewModel(initialData));
当我选择类型为无时,它选择所有汽车,如果我选择除无以外的类型,那么它应该只选择“充电器”和“万能”
以下是fiddle
的链接答案 0 :(得分:1)
首先,如果要返回所有项目,只需返回self.items()
,则不需要切片。
如果要返回与过滤器匹配的项目,则应该可以:
self.filteredItems = ko.computed(function() {
var myFilter = self.filter();
if (!myFilter || myFilter == "None") {
return self.items();
} else {
var tempArray = [];
for(i=0; i<self.items().length; i++) {
if(self.items()[i].type == myFilter) {
tempArray.push(self.items()[i]);
}
}
return tempArray;
}
});
检查工作fiddle。
如果你想在这里只选择“Charger”和“Magnum”:
self.filteredItems = ko.computed(function() {
var myFilter = self.filter();
if (!myFilter || myFilter == "None") {
return self.items();
} else {
return [ self.items()[1], self.items()[3] ];
}
});