1

当我更改 B 列中的选择时,A 列中的文本也应该更改,但不会更改。为什么?

HTML:

    <table>
    <thead>
        <tr>
            <th style="width: 100px;">A</th>
            <th style="width: 100px;">B</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: Data">
        <tr>
            <td><span data-bind="text: idOpt"></span></td>
            <td><select data-bind="options: $root.MyOptions, optionsText: 'name', optionsValue: 'id', value: idOpt"></select></td>
        </tr>
    </tbody>
</table>

JS:

function AppViewModel() {
   var self = this;
   self.MyOptions = ko.observableArray([
       {id: 'a1', name: 'One'},
       {id: 'a2', name: 'Two'},
       {id: 'a3', name: 'Three'}
   ]);

   self.Data = ko.observableArray([
       {idOpt: 'a1'},
       {idOpt: 'a2'},
       {idOpt: 'a1'}
   ]);
}

var vm = new AppViewModel();
ko.applyBindings(vm);

http://jsfiddle.net/bnowicki/CrVBr/2/

请帮忙。

4

1 回答 1

2

如果您希望它们绑定/更新,则必须将 Data 数组中的项目声明为可观察对象。

function AppViewModel() {
   var self = this;
   self.MyOptions = ko.observableArray([
       {id: 'a1', name: 'One'},
       {id: 'a2', name: 'Two'},
       {id: 'a3', name: 'Three'}
   ]);

   self.Data = ko.observableArray([
       {idOpt: ko.observable('a1')},
       {idOpt: ko.observable('a2')},
       {idOpt: ko.observable('a1')}
   ]);
}

var vm = new AppViewModel();
ko.applyBindings(vm);

Knockout 文档向您展示了使用普通模型和使用 observables 模型之间的区别http://knockoutjs.com/documentation/observables.html

于 2013-10-01T22:40:05.443 回答