【问题标题】:Initializing a Bootstrap accordion menu in Knockout在 Knockout 中初始化 Bootstrap 手风琴菜单
【发布时间】:2016-01-07 16:04:11
【问题描述】:

这是我的手风琴菜单示例,它应该使用与 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());
<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>

【问题讨论】:

    标签: twitter-bootstrap knockout.js data-binding twitter-bootstrap-3 knockout-2.0


    【解决方案1】:

    你应该:

    1. 用逗号分隔你的foreach 参数,正如@Roy J 在下面写的那样,child 应该用引号括起来: "foreach: { data: tree.children, as: 'child'}" 而不是 foreach: { data: tree.children as: child}

    2. this.tree = ko.observable(confItems);更改为this.tree = confItems;

    检查小提琴 - Fiddle

    【讨论】:

    • 并且孩子应该用引号引起来。
    • 逗号是拼写错误。我问的主要问题是该方法是否正确,但感谢您发现这样的小问题。
    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2020-03-08
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    相关资源
    最近更新 更多