html:
<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>
</table>
<select data-bind="foreach: seats">
<option data-bind="text: name;value:text: meal().price"></option>
</select>
js代码:
// 一个构造函数
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
//数据模型
function ReservationsViewModel() {
var self = this;
//数据
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
// 监控数组
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[1])
]);
}
//传递数据
ko.applyBindings(new ReservationsViewModel());
效果页:
Your seat reservations
Passenger name | Meal | Surcharge | |
---|---|---|---|
Steve | Standard (sandwich) | 0 | |
Bert | Premium (lobster) | 34.95 |