html代码
$index + 1使得索引从1开始
<div class="table-responsive"> <table id="cpaAcctAppList" align="center" class="table table-striped table-bordered table-hover table-fix"> <thead> <tr> <th width="50">序号 </th> <th width="70">操作 </th> <th width="150">流程名称 </th> </tr> </thead> <tbody data-bind="foreach: items"> <tr> <td data-bind="text: $index() + 1"></td> <td><a href="#" data-bind="click: $root.showItemIndex">点击显示索引</a></td> <td data-bind="text: $data"></td> </tr> </tbody> </table> </div>
javascript代码
$(function () { // initTable(); var vm = new TableViewModel(); ko.applyBindings(vm,$('#cpaAcctAppList')[0]); vm.init(); }); function TableViewModel() { var self = this; self.items = ko.observableArray([]); self.showItemIndex = function(item, event) { var context = ko.contextFor(event.target); //获取绑定元素的上下文;event.target绑定View Model的DOM元素 var index = context.$index(); console.log("当前索引是:" + index); }; self.init = function() { $.postAjax(baseUrl + 'query',{flowName : $.trim(queryFormVM.flowName())},function (data) { var arr = []; for (var i = 0; i < data.length; i++) { arr[i] = data[i].flowId; arr[i] = data[i].flowName; arr[i] = data[i].flowDesc; } self.items(arr); }); }; }