在嵌套循环中获取祖父母的$ index [英] Getting $index of grand parent in a nested loop
问题描述
如何在嵌套循环中访问祖父母的索引?
How to access the index of the grand parent in the nested loop?
例如:
<div class="loop" data-bind="foreach: rows">
<div class="nested-loop" data-bind="foreach: cells">
<div class ="nested-nested-loop" data-bind="foreach: candidates, css : {selected : $root.isSelected($parentContext.$parentContext.$index(), $parentContext.$index(), $index())}">
Candidate index: <span data-bind="text: $index()"></span>
Cell index: <span data-bind="text: $parentContext.$index()"></span>
Row index: <span data-bind="text: $parentContext.$parentContext.$index()"></span>
</div>
</div>
</div>
我试图这样绑定:
css : {selected : $root.isSelected($parentContext.$parentContext.$index(), $parentContext.$index(), $index())}
我遇到了:
TypeError:
$parentContext.$parentContext.$index
不是函数
推荐答案
如果要显示祖父母的索引,则需要$parentContext
的$parentContext
,因此需要编写:
If you want to display the index form the grand-parent you need the $parentContext
of the $parentContext
, so you need to write:
Row index: <span data-bind="text: $parentContext.$parentContext.$index()"></span>
它在您的css
绑定中不起作用,因为您在与foreach
相同的元素上具有绑定,因此在绑定点处未正确设置绑定上下文.
It is not working in your css
binding because you have the binding on the same element as your foreach
so the binding context is not correctly set at their point.
您可以通过在不同元素上移动foearch
和css
来解决此问题,例如使用无容器绑定系统税:
You can solve this with moving the foearch
and the css
on different elements like using the containrless binding systax:
<div class="loop" data-bind="foreach: rows">
<div class="nested-loop" data-bind="foreach: cells">
<!-- ko foreach: candidates -->
<div class="nested-nested-loop"
data-bind="css : {selected :
$root.isSelected($parentContext.$parentContext.$index(),
$parentContext.$index(), $index())}">
Candidate index: <span data-bind="text: $index()"></span>
Cell index: <span data-bind="text: $parentContext.$index()"></span>
Row index: <span
data-bind="text: $parentContext.$parentContext.$index()"></span>
</div>
<!-- /ko -->
</div>
</div>
演示 JSFiddle .
这篇关于在嵌套循环中获取祖父母的$ index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!