如何将列添加到表中

时间:2012-12-27 08:57:39

标签: javascript knockout.js

这是示例代码knockout.js:

<h2>Your seat reservations</h2>

<table>
    <thead><tr>
        <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
    </tr></thead>
    <tbody data-bind="foreach: seats">
    <tr>
        <td data-bind="text: name"></td>
        <td data-bind="text: meal().mealName"></td>
        <td data-bind="text: meal().price"></td>
    </tr>    
</tbody>
    <tbody><button data-bind="click: addSeat">Reserve another seat</button></tbody>
</table>

JS:

// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];    

    // Editable data
    self.seats = ko.observableArray([
        new SeatReservation("Steve", self.availableMeals[0]),
        new SeatReservation("Bert", self.availableMeals[1])
    ]);

    self.addSeat = function() {
        self.seats.push(new SeatReservation("12321", self.availableMeals[0]));
    }
}

ko.applyBindings(new ReservationsViewModel());

此代码适用于添加列。但我需要专栏,有可能吗?

1 个答案:

答案 0 :(得分:1)

在ReservationViewModel中添加以下行,并将标题替换为

下面的html部分
self.Columns = ko.observableArray([{ ColumnName: "Header1" }, { ColumnName: "Header2"}]);


 <tr data-bind="foreach: Columns">
            <th data-bind="text: ColumnName>
                Passenger name
            </th>
        </tr>

希望这会对你有所帮助