我有一些代码列出了一些带有复选框的类别和子类别,但我无法显示已在嵌套ul中检查了哪些复选框。它确实返回所选项目,但不在ul列表中。
请告诉我如何在嵌套ul中显示所选类别和子目录。感谢。
var ViewModel = function() {
var self = this;
self.selectedCategories = ko.observableArray();
self.selectedItems = ko.observableArray();
self.categories = ko.observableArray([
{ name: 'Hospitality', items: [ 'Bars', 'Caterers', 'Cafes', 'Food To Go', 'Pubs' ] },
{ name: 'Popup', items: [ 'Food Vans', 'Festivals', 'Markets', 'Beer Garden' ] }
]);
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
<ul data-bind="foreach: { data: categories, as: 'category' }">
<li> <input type="checkbox" name="level-1" data-bind="checked: $root.selectedCategories, attr: {value: name}"><span data-bind="text: category.name"></span></input>
<ul data-bind="foreach: { data: items, as: 'item' }">
<li><input type="checkbox" name="level-2" data-bind="checked: $root.selectedItems, attr: {value: item}"><span data-bind="text: item"></span></input></li>
</ul>
</li>
</ul>
<div data-bind="text: selectedCategories"></div>
<div data-bind="text: selectedItems"></div>
答案 0 :(得分:0)
我建议在类别自己的模型中存储是否选择了类别及其选定的项目。您可以在computed
中设置ViewModel
来创建仅包含所选类别的数组。这是一个例子:
var ViewModel = function() {
var self = this;
self.categories = ko.observableArray([{
name: 'Hospitality',
items: ['Bars', 'Caterers', 'Cafes', 'Food To Go', 'Pubs'],
selected: ko.observable(false),
selectedItems: ko.observableArray([])
}, {
name: 'Popup',
items: ['Food Vans', 'Festivals', 'Markets', 'Beer Garden'],
selected: ko.observable(false),
selectedItems: ko.observableArray([])
}]);
self.selectedCategories = ko.computed(function() {
return self.categories().filter(function(cat) {
return cat.selected()
});
});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: { data: categories, as: 'category' }">
<li>
<input type="checkbox" name="level-1"
data-bind="checked: selected, value: name">
<span data-bind="text: name"></span>
<ul data-bind="foreach: { data: items, as: 'item' }">
<li>
<input type="checkbox" name="level-2"
data-bind="checked: category.selectedItems, value: item, enable: category.selected">
<span data-bind="text: item, style: { 'opacity' : (category.selected() ? 1 : 0.5)}"></span>
</li>
</ul>
</li>
</ul>
<h2>Selections</h2>
<ul data-bind="foreach: selectedCategories">
<li>
<div data-bind="text: name"></div>
<ul data-bind="foreach: selectedItems">
<li data-bind="text: $data"></li>
</ul>
</li>
</ul>
注意:您的代码段中包含一些无效的HTML:您无法在<span>
元素中添加<input>
元素。