以下是我应该使用与JSON兼容的格式的手风琴菜单示例。我有一个数据结构,但数据和HTML之间的绑定不起作用。我应该在2级菜单中显示这种多级结构?
var confItems = {
"children":ko.observableArray()
};
var childrenLength = 3;
console.log("A",confItems);
for (var i = 0; i < childrenLength; i++) {
confItems.children.push({
"idhash": ko.observable("#col-" + (i + 1)),
"id": ko.observable("col-"+ (i + 1)),
"displayLabel": ko.observable("Item " + (i + 1)),
"children": ko.observableArray()
});
console.log("B",confItems);
for (var j = 0; j < childrenLength; j++) {
confItems.children()[i].children().push({
"idhash": ko.observable("#col-" + (i + 1) + "-" + (j + 1)),
"id": ko.observable("col-" + (i + 1) + "-" + (j + 1)),
"displayLabel": ko.observable("Item " + (i + 1) + "." + (j + 1)),
"children": ko.observableArray()
});
console.log("C",confItems);
}
console.log("D",confItems);
}
console.log(confItems);
var viewModel = function() {
this.tree = ko.observable(confItems);
};
ko.applyBindings(new viewModel());
&#13;
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="panel-group">
<div id="accordion" class="panel panel-default" data-bind="foreach: { data: tree.children, as: child}">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion"
data-bind="text:child.displayLabel, attr:{href:child.idhash}">First level</a>
</h4>
</div>
<div data-bind="attr:{id:child.id}" class="panel-collapse collapse">
<div class="panel-body" data-bind="foreach: { data: child.children, as: child}">
<div class="panel-heading">
<a data-bind="text:child.displayLabel">Second level</a>
</div>
</div>
</div>
</div>
</div>
&#13;
答案 0 :(得分:1)
你应该:
用逗号分隔你的foreach
参数,正如@Roy J在下面写的那样,child应该用引号括起来:
"foreach: { data: tree.children, as: 'child'}"
代替foreach: { data: tree.children as: child}
将this.tree = ko.observable(confItems);
更改为this.tree = confItems;
检查小提琴 - Fiddle