简体   繁体   English

在knockout js中找到foreach data-bind的最后一次迭代

[英]Find the last iteration of foreach data-bind in knockout js

Is there a way to find last iteration using foreach data-bind in knockout js? 有没有办法在淘汰赛中使用foreach data-bind找到最后一次迭代?

My problem is, I am iterating over a list of items and want to print all items separated by a line. 我的问题是,我正在迭代一个项目列表,并希望打印由一行分隔的所有项目。

I don't want to draw a line(hr) for the last item of that array. 我不想为该数组的最后一项绘制一条线(hr)。

Inside of a foreach, you can bind against a special context variable (observable) called $index . 在foreach中,您可以绑定一个名为$index的特殊上下文变量(observable)。 So, you could bind something like visible: $index() < $parent.items().length - 1 . 所以,你可以绑定像visible: $index() < $parent.items().length - 1这样的东西visible: $index() < $parent.items().length - 1

Sample: http://jsfiddle.net/rniemeyer/M55qh/ 示例: http//jsfiddle.net/rniemeyer/M55qh/

You can check if you are displaying the first element. 您可以检查是否显示第一个元素。

<div data-bind="foreach: items">
   <hr data-bind="visible : $index()!=0" /> 
   <span data-bind="text: $data"></span>
</div>

See fiddle 看小提琴

Or as RP Niemeyer said, you can omit the last hr : 或者正如RP Niemeyer所说,你可以省略最后一小时:

<div data-bind="foreach: items">
   <span data-bind="text: $data"></span>
   <hr data-bind="visible : $index() != ($parent.length-1)" /> 
   // notice the hr is after the item.
</div>

With CSS maybe you can use last-child , try: 使用CSS也许你可以使用last-child ,尝试:

hr:last-child {
  display:none;
}

And if you can be more specific like adding the id of parent container. 如果您可以更具体地添加父容器的id

Could you use visible: $index() < list().length or something similar? 你可以使用visible: $index() < list().length或类似的东西?

http://jsfiddle.net/x2aa7/ http://jsfiddle.net/x2aa7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM