在嵌套循环中获取祖父母的$ index [英] Getting $index of grand parent in a nested loop

查看:95
本文介绍了在嵌套循环中获取祖父母的$ index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在嵌套循环中访问祖父母的索引?

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>

http://jsfiddle.net/fjYsG/

它在您的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.

您可以通过在不同元素上移动foearchcss来解决此问题,例如使用无容器绑定系统税:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆