1

我正在研究 knockout.js。我对knockout.js 很陌生,所以我正在关注knockout.js 教程。我试图在下拉列表中显示项目列表,基本上它是 knockout.js 教程中提供的实际示例。我写了以下代码,

<script type="text/javascript">
        $(document).ready(function () {
            function setreservation(name, initmeal) {
                var self = this;
                self.Name = name;
                self.Meal = ko.observable(initmeal);

                self.FormatPrice = ko.computed(function () {
                    return self.Meal().Price ? "$" + self.Meal().Price.toFixed(2) : "none";
                });
            }

            function ReservationViewModel() {
                var self = this;
                self.availablemeals = [{ "MealName": "standard", "Price": 10 }, { "MealName": "premium", "Price": 20 }, { "MealName": "Platinum", "Price": 30}];
                self.seats = ko.observableArray([new setreservation("karthik", self.availablemeals[0]), new setreservation("Tirumalesh", self.availablemeals[1])]);
                self.ReserveNewSeat = function () {
                    self.seats.push(new setreservation("karhik", self.availablemeals[2]));
                };
            }

            ko.applyBindings(new ReservationViewModel());
        }); 

我的看法是,

<table cellpadding="3" cellspacing="4">
<thead>
<tr>
<th>Name</th><th>Meal</th><th>Price</th>
</tr>
</thead>
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value:Name" /> 
</td>
<td><select data-bind="options:$root.availablemeals,value:Meal,optionsText:MealName"></select></td>
<td data-bind="text:FormatPrice"></td>
</tr>
</tbody>
</table>
<button data-bind="click:ReserveNewSeat">Reserve New One</button>

所以请指导我我的代码是否有任何问题。

4

1 回答 1

3

你错过''optionsText绑定:

<select data-bind="options: $root.availablemeals, value: Meal, optionsText: 'MealName'">

这是工作小提琴:http: //jsfiddle.net/vyshniakov/DRDGK/

于 2012-10-16T13:24:56.287 回答