2013-06-06 15 views
1

我給了Knockout的foreach的每個數據的別名,所以我可以在另一個嵌套的foreach中調用它。 現在我想獲取別名的索引。我試過'.index()'和'。$ index'但沒用。在Knockoutjs中獲取foreach別名的索引

<!-- ko foreach: {data: subjects, as: 'subject' }--> 
/*nested foreach*/ 
subject.index() <-- undefined 
<!-- /ko--> 

請幫幫忙,謝謝

回答

6

您可以使用非標準的javascript函數Array.indexOf()

<!-- ko foreach: {data: subjects, as: 'subject' }--> 
/*nested foreach*/ 
    <span data-bind="text: subjects.indexOf(subject)"></span> 
<!-- /ko--> 

$index上下文值可以使用只適用於非虛擬的for-each,例如

<ul data-bind="foreach: categories"> 
    <span data-bind="text: $index"></span> 
</ul>