监控数组与foreach绑定Knockout.js

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(nameinitialMeal{
    var self this;
    self.name name;
    self.meal ko.observable(initialMeal);
}

//数据模型
function ReservationsViewModel({
    var self this;

    //数据
    self.availableMeals [
        mealName"Standard (sandwich)"price},
        mealName"Premium (lobster)"price34.95 },
        mealName"Ultimate (whole zebra)"price290 }
    ];    

    // 监控数组
    self.seats ko.observableArray([
        new SeatReservation("Steve"self.availableMeals[0]),
        new SeatReservation("Bert"self.availableMeals[1])
    ]);
}
//传递数据
ko.applyBindings(new ReservationsViewModel());

效果页:

Your seat reservations

Passenger nameMealSurcharge 
Steve Standard (sandwich) 0
Bert Premium (lobster) 34.95

原文地址:https://www.cnblogs.com/lbonet/p/6482765.html