0

为了让附加的代码正常工作,我几乎整天都在沮丧地玩耍。代码或多或少取自http://jsfiddle.net/rniemeyer/5Xr2X/。我的版本显示第一页,IE,前 10 行。单击下一步会触发 pagedRows 函数,但不会在我的一生中显示下一页数据。嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻

附上代码

<table>
   <tr>
       <th>Id</th>
       <th>Type</th>
       <th>Name</th>
    </tr>
  <tbody data-bind='template: { name: "fieldTemplate", foreach: pagedRows }'></tbody>
</table>

<a href="#" data-bind="click: previous, visible: pageIndex() > 0">Previous</a>
<a href="#" data-bind="click: next, visible: pageIndex() < maxPageIndex()">Next</a>

<script type="text/html" id="fieldTemplate">
    <tr>
         <td><span data-bind="text:FieldId" /></td>
         <td><span data-bind="text:Type" /></td>
         <td><span data-bind="text:Description" /></td>
    </tr>
</script>

<script>
    function ViewModel(jsondata) {
        var self = this;
        self.fields = ko.observableArray(jsondata);
        self.pageIndex = ko.observable(0);
        self.pageSize = ko.observable(10);

        self.pagedRows = ko.computed(function () {
            var size = self.pageSize();
            var start = self.pageIndex() * size;
            return self.fields.slice(start, start + size);
        });

        self.maxPageIndex = ko.computed(function () {
            return Math.ceil(self.fields().length / self.pageSize()) - 1;
        });

        self.next = function () {
            self.pageIndex(self.pageIndex + 1);
        }
        self.previous = function () {
            self.pageIndex(self.pageIndex - 1);
        }
    }

    $(function () {
        var data = [];
        for (var i = 0; i < 100; i++) {
            data.push({
                FieldId: i,
                Type: "Type" + i,
                Name: "Name" + i,
                Description: "Description" + i
            })
        }

        ko.applyBindings(new ViewModel(data));

    });
</script>

看起来非常直截了当,但我就是不明白。任何帮助将不胜感激。

谢谢

麦克风

4

1 回答 1

2

当您执行下一个/上一个操作时,您需要通过将其作为函数调用来检索 observable 的值并从中加减 1。所以,你会想做:

self.next = function() {
    self.pageIndex(self.pageIndex() + 1);
}
self.previous = function() {
    self.pageIndex(self.pageIndex() - 1);
}
于 2012-11-15T01:07:07.950 回答