这是我使用knockout.js的第一个项目,我遇到了一个无法解决的问题。我试图让foreach绑定3级深度。前两个级别有效,但第三个级别没有。我的HTML或JavaScript都没有看错。
<div class="skill-list-body">
<div class="inner-skill-list-body">
<div class="skill-list-publication-title" data-bind="text: publication"></div>
<div data-bind="foreach: { data: categories, as: 'category' }">
<div>
<div class="skill-list-category-title" data-bind="text: category.name"></div>
<div class="category-container" data-bind="foreach: { data: realms, as: 'realm' } ">
<div class="realm-skill-box">
<div class="skill-list-realm-heading" data-bind="text: name">
<div data-bind="foreach: { data: skills, as: 'skill' }">
<div data-bind="text: skill.name"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
的JavaScript
var viewModel = {
publication: 'Medieval Fantasy Skills',
categories: ko.observableArray([
{
name: 'Physical & Social Combat Skills',
realms: ko.observableArray([
{
name: 'The Realm of Combat Tactics Skills',
skills: ko.observableArray([
{ name: 'Craft Profession', id: 0 }
])
}
])
}
])
};
ko.applyBindings(viewModel);
答案 0 :(得分:1)
您需要关闭名称div标签以打开foreachthe binding -
<div class="skill-list-realm-heading" data-bind="text: name">
</div>
<div data-bind="foreach: { data: skills, as: 'skill' }">
<div data-bind="text: skill.name"></div>
</div>
这是因为名称绑定会覆盖包含foreach循环的innerHtml
答案 1 :(得分:1)
这就是问题所在:
<div class="skill-list-realm-heading" data-bind="text: name">
<div data-bind="foreach: { data: skills, as: 'skill' }, ">
<div data-bind="text: skill.name"></div>
</div>
</div>
您的外部name
绑定有效地清除了节点的内容。让技能成为节点的兄弟,而不是孩子。
<div class="skill-list-realm-heading" data-bind="text: name"></div>
<div data-bind="foreach: { data: skills, as: 'skill' }, ">
<div data-bind="text: skill.name"></div>
</div>