Knockout.js 获取observableArray索引,并在敲除JS中计算

Knockout.js 获取observableArray索引,并在敲除JS中计算,knockout.js,Knockout.js,我想用UI绑定GuestNumber字段如何计算GuestNumber字段 var GuestLine = function () { var self = this; self.FirstName = ko.observable(); self.LastName = ko.observable(); self.Email = ko.observable(); this.GuestNumber = ko.comput

我想用UI绑定
GuestNumber
字段如何计算
GuestNumber
字段

var GuestLine = function () {
        var self = this;
        self.FirstName = ko.observable();
        self.LastName = ko.observable();
        self.Email = ko.observable();
        this.GuestNumber = ko.computed(function() {
            return this.index;
        }, this);
    };


    var Cart = function () {
        // Stores an array of lines, and from these, can work out the grandTotal
        var self = this;
        self.Guests = ko.observableArray([new GuestLine()]); // Put one line in by default
        self.ParticipantFirstName = ko.observable();
        self.ParticipantLastName = ko.observable();
        self.ParticipantEmail= ko.observable();

        // Operations
        self.addLine = function () { self.Guests.push(new GuestLine()); };
        self.removeLine = function (line) { self.lines.remove(line); };
        self.save = function () {

            var dataToSave = ko.mapping.toJSON(self);

            $.ajax({
                type: 'POST',
                url: '/API/RSVPHandlerService.ashx',
                data: dataToSave,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (r) {
                    alert(r.d.Name);
                    alert(r.d.Population);
                }
            });


        };
    };
    $(function () {
        ko.applyBindings(new Cart());
    });

您最好使用
$index
。示例2显示了如何执行此操作:

  • 职位名称:
<h4>People</h4>
<ul data-bind="foreach: people">
    <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
    </li>
</ul>