请查找我的html代码如下。
<ul data-bind="foreach: globalMenuItems " style='background:red'>
<li>
<a class="ms-core-suiteLink-a" data-bind="attr: { href:URL }"><span data-bind="text: name"></span></a>
</li>
</ul>
Javascript文件代码如下
function renderTerm(term) {
console.log(term)
var newMenuItem = new MenuItem(term);
if (term.term.get_isRoot() && term.children.length > 0) {
newMenuItem.SubMenuItem.push(term)
ElsaGlobalNavigation.GlobalNavigation.viewModel.globalMenuItems.push(newMenuItem);
var html = '<li class="dropdown"><a href="' + term.URL + '">' + term.name + '<span class="caret"></span></a>';
} else if (term.children.length > 0) {
console.log(ElsaGlobalNavigation.GlobalNavigation.viewModel.globalMenuItems)
newMenuItem.SubMenuItem.push(term);
ElsaGlobalNavigation.GlobalNavigation.viewModel.globalMenuItems.push(newMenuItem);
// ElsaGlobalNavigation.GlobalNavigation.viewModel.globalMenuItems.push(term);
var html = '<li class="dropdown-submenu"><a href="' + term.URL + '">' + term.name + '</a>';
} else {
console.log(ElsaGlobalNavigation.GlobalNavigation.viewModel.globalMenuItems)
var html = '<li><a href="' + term.URL + '">' + term.name + '</a>';
count++;
ElsaGlobalNavigation.GlobalNavigation.viewModel.globalMenuItems.push(newMenuItem);
}
if (term.children && term.children.length) {
html += '<ul class="dropdown-menu">';
for (var i = 0; i < term.children.length; i++) {
html += renderTerm(term.children[i]);
}
html += '</ul>';
}
return html + '</li>';
}
目前,代码显示单个ul下的所有li,我想要ul li树结构。正如你可以看到图像,我想要淘汰js部分看起来像左侧html ul li树结构图像。
答案 0 :(得分:1)
关于你的viewmodel如何布局的一些缺失信息,所以我使用数组items
在挖空中重新创建了一个非常基本的3级列表,该数组item.children
还可以在{{1}中包含更多项目列表}。
我希望有助于弄清楚如何将其包含在这个特定的实现中:
var viewModel = {
items: [
{
name: "About Us"
},
{
name: "Library",
children: [
{
name: "Books",
children: [
{ name: "Book1" },
{ name: "Book2" }
]
}
]
},
{
name: "News"
}
]
}
ko.applyBindings(viewModel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul class="tree-depth-1" data-bind="foreach: items">
<li>
<span data-bind="text: name"></span>
<!-- depth 2 -->
<ul class="tree-depth-2" data-bind="foreach: $data.children">
<li>
<span data-bind="text: name"></span>
<!-- depth 3 -->
<ul class="tree-depth-3" data-bind="foreach: $data.children">
<li>
<span data-bind="text: name"></span>
</li>
</ul>
</li>
</ul>
</li>
</ul>