我有一個可觀察數組,我在select元素中顯示,例如,如果我有4個元素在數組中,那麼我將有4個選擇元素。如何通過選擇元素更新Observable Array的值
當我改變選擇列表中的項目時,可觀察數組似乎沒有改變。
請幫助我如何更新observable數組。
的一樣的jsfiddle是here
HTML代碼
<div>
<div>
<table>
<th>Name</th>
<th>Age</th>
<th>Country</th>
<tbody data-bind="foreach: players">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: age"></td>
<td data-bind="text: country"></td>
<td data-bind="text: trophies"></td>
<td>
<button data-bind="click: $root.editPlayers">Edit</button>
</td>
</tr>
</tbody>
</table>
</div>
<div data-bind="with: editPlayer">
<h3>Edit</h3>
Name:
<input type="text" data-bind="value: name" />
<br/>Age:
<input type="text" data-bind="value: age" />
<br/>Country:
<input type="text" data-bind="value: country" />
<span data-bind="foreach: trophies">
<br/>Tropies:
<select data-bind="options: $root.trophiesList, value:$data, optionsCaption:'Choose..'"></select>
</span>
</div>
</div>
JavaScript代碼
var player = function (name, age, country, trophyArray) {
this.name = ko.observable(name);
this.age = ko.observable(age);
this.country = ko.observable(country);
this.trophies = ko.observableArray(trophyArray);
};
var playerModel = function() {
var self = this;
self.players = [
new player('Roger', 32, 'swiss', ['AO','FO','WB','US']),
new player('Murray', 28, 'Scott', ['WB','US'])];
self.editPlayer = ko.observable();
self.trophiesList = ['AO','US','FO', 'WB'];
self.editPlayers = function (player) {
self.editPlayer(player);
}
}
ko.applyBindings(new playerModel());
JSFiddler指着一個老版本,我已經更新了鏈接再次 – Swamy
你的模式是錯誤的。你不會爲每個選項做一個選項,只需使用可觀察數組設置選項參數,那麼值參數應該與selectedTrophy類似。再次檢查文檔 –
@ bto.rdz我有一個獎盃的列表,我在一個單獨的select元素中顯示每個獎盃,允許每個都改變。可能我也會嘗試多選擇選項。 – Swamy