Javascript Knockout.js 使用 $index 和 if 绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11318441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:25:48  来源:igfitidea点击:

knockout.js using $index with if binding

javascriptknockout.js

提问by user1255162

I'm trying to show some mark up based on the value of $index, I can display the value but I can't seem to use it with an ifbinding, what's the best approach here?

我试图根据 的值显示一些标记$index,我可以显示该值,但我似乎无法将它与if绑定一起使用,这里最好的方法是什么?

<!-- ko if: $index===0 -->
  <div>some mark up here</div>
<!-- /ko -->

回答by John Earles

$index is an observable, and observables are functions. When you use observables in an expression you must use the () form to access the value.

$index 是一个 observable,而 observables 是函数。在表达式中使用 observable 时,必须使用 () 形式来访问值。

<!-- ko if: $index() === 0 -->

回答by HymanMorrissey

From the knockout bindings page

淘汰赛绑定页面

$index (only available within foreach bindings)

This is the zero-based index of the current array entry being rendered by a foreach binding. Unlike the other binding context properties, $index is an observable and is updated whenever the index of the item changes (e.g., if items are added to or removed from the array).

$index(仅在 foreach 绑定中可用)

这是由 foreach 绑定呈现的当前数组条目的从零开始的索引。与其他绑定上下文属性不同,$index 是一个 observable 并且在项目的索引发生变化时更新(例如,如果项目添加到数组或从数组中删除)。

Example

例子

<div data-bind="foreach: details.additionalDetails">
    <!-- ko if: $index() !== 0 -->
        <span> | </span>
     <!-- /ko -->
        <span data-bind="text: name"></span> <span data-bind="text: value"></span>
</div>

Results in

结果是

Model #: UAI5021 | Catalog #: UIOY786