如何在Knockout.js模板中访问项目的索引 [英] How to access the index of an item in knockout.js template

查看:61
本文介绍了如何在Knockout.js模板中访问项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的tbody模板中,如何访问正在渲染的项目的索引?

Within my template in tbody below, how can I access the index of the item being rendered?

<table>
        <tbody data-bind="foreach:contacts">
            <tr class="contactRow" valign="top">
            <td><a href="#" data-bind="click: function(){viewModel.removeContact($data)}">Delete</td>
            <td><input data-bind="value: FirstName" name="Contacts[].FirstName"/></td>
            <td><input data-bind="value: LastName" name= "Contacts[].LastName"  /></td>
            <td><input data-bind="value: Username"  name="Contacts[].Username"/></td>
            <td><input data-bind="value: Email"   name="Contacts[].Email"/></td>
        </tr>
        </tbody>
        <thead>
            <tr>
                <th>Controls</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Username</th>
                <th>Email</th>
            </tr>
        </thead>
    </table>

推荐答案

更新:$index现在在KO 2.1中可用.

Update: $index is now available in KO 2.1.

当前,没有一种方法可以直接访问foreach中的索引.有一个请求请求,要求在此处添加$index变量: https://github.com/SteveSanderson/knockout/拉/182

Currently, there is not a way to directly access the index in a foreach. There is a pull request that looks at adding a $index variable here: https://github.com/SteveSanderson/knockout/pull/182

我过去使用的一个选项是对observableArray使用手动订阅,以使索引可同步观察.

An option that I have used in the past is to use a manual subscription against an observableArray that keeps an index observable in sync.

它的工作原理是:

//attach index to items whenever array changes
viewModel.tasks.subscribe(function() {
    var tasks = this.tasks();
    for (var i = 0, j = tasks.length; i < j; i++) {
       var task = tasks[i];
        if (!task.index) {
           task.index = ko.observable(i);  
        } else {
           task.index(i);   
        }
    }
}, viewModel);

以下是示例: http://jsfiddle.net/rniemeyer/CXBFN/

这篇关于如何在Knockout.js模板中访问项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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