【发布时间】:2019-04-29 06:34:31
【问题描述】:
使用 knocoutJs 选择品牌和型号时如何在 div 循环中显示文本和年份
这样
梅赛德斯>C
*C-180
*2016
*C-200
*2015
HTML
<select data-bind="options: manufacturers, optionsCaption:'Brand', optionsText: 'text', optionsValue: 'value', value: selectedManufacturer"></select>
<select data-bind="options: models, optionsCaption:'Model', optionsText: 'text', optionsValue: 'value', value: selectedModel, enable: models().length"></select>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-debug.js">
JavaScript (KnockoutJS)
function ViewModel(items) {
this.manufacturers = ko.observableArray(items);
this.selectedManufacturer = ko.observable();
this.selectedModel = ko.observable();
function getById(items, value) {
if(!value) {
return [];
}
var result = ko.utils.arrayFirst(items, function(item) {
return item.value === value;
});
return result && result.childItems || [];
}
this.models = ko.computed(function(){
var items = this.manufacturers();
var id = this.selectedManufacturer()
return getById(items, id);
}, this);
}
var items = [
{ text: 'Ford', value: 1, childItems:
[
{ text: 'Mustang', value: 1, childItems:
[
{ text: 'Shelby GT 350', year: "2015", value: 1, childItems: [] },
{ text: 'Shelby GT 500', year: "2017", value: 2, childItems: [] }
]
},
{ text: 'Focus', value: 2, childItems:
[
{ text: 'Focus RS', year: "2017", value: 3, childItems: [] },
{ text: 'Focus S', year: "2014", value: 4, childItems: [] }
]
}
]
},
{ text: 'Mercedes', value: 2, childItems:
[
{ text: 'S', value: 5, childItems:
[
{ text: 'S-400', year: "2018", value: 5, childItems: [] },
{ text: 'S-350', year: "2014", value: 6, childItems: [] }
]
},
{ text: 'C', id: 6, childItems:
[
{ text: 'C-180', year: "2016", value: 7, childItems: [] },
{ text: 'C-200', year: "2015", value: 8, childItems: [] }
]
}
]
}
];
var module = {};
module.viewModel = new ViewModel(items);
ko.applyBindings(module.viewModel);
【问题讨论】:
标签: javascript jquery arrays knockout.js nested