可能會涉及這種錯誤的方式,但我有一個使用foreach使用knockout可觀察數組填充的html表。在每一行我有一個下拉。我喜歡jquery ui選擇菜單,所以我正在使用它。不幸的是,當您運行小提琴時,您會注意到,在更新下拉菜單時,相應的淘汰賽選定值未被更新。同步jquery ui選擇菜單與淘汰賽可觀察陣列
這裏是小提琴https://jsfiddle.net/8rw4ruze/3/ 這裏是html。
<table class="table table-condensed table-responsive">
<thead>
<th>id</th>
<th>animal</th>
<th>Selected Value</th>
</thead>
<tbody data-bind="foreach: tableRows">
<tr>
<td data-bind="text: id"></td>
<td>
<select class="form-control" data-bind="options: recordList,
optionsText: 'desc',
optionsValue: 'val',
value: selectedVal,
attr: {id: selectId}">
</select>
</td>
<td data-bind="text: selectedVal"></td>
</tr>
</tbody>
</table>
這裏是JavaScript
function record(val, desc) {
var self = this;
this.val = ko.observable(val);
this.desc = ko.observable(desc);
}
function tableRow(id, recordList) {
var self = this;
this.id = ko.observable(id);
this.recordList = ko.observable(recordList)
this.selectedVal = ko.observable('A');
this.selectId = ko.computed(function() {
return 'mySelect' + self.id()
}, this);
}
function Model() {
var self = this;
this.records = ko.observableArray("");
this.tableRows = ko.observableArray("");
}
var mymodel = new Model();
$(function() {
mymodel.records.push(new record('A', 'ant'));
mymodel.records.push(new record('B', 'bird'));
mymodel.records.push(new record('C', 'cat'));
mymodel.records.push(new record('D', 'dog'));
mymodel.tableRows.push(new tableRow(1, mymodel.records()));
mymodel.tableRows.push(new tableRow(2, mymodel.records()));
mymodel.tableRows.push(new tableRow(3, mymodel.records()));
mymodel.tableRows.push(new tableRow(4, mymodel.records()));
ko.applyBindings(mymodel);
for (var i = 0; i < 4; i++) {
var id = '#mySelect' + (i + 1)
$(id).selectmenu({
width: 125,
change: function(event, ui) {
var newVal = $(this).val();
mymodel.tableRows()[i].selectedVal(newVal);
}
});
}
});
感謝所有我與數據屬性去。我更喜歡使用自定義綁定,但我不夠聰明來弄清楚,所以我就這樣做了。
for (var i = 0; i < 4; i++) {
var id = '#mySelect' + (i + 1)
$(id).selectmenu({
width: 125,
change: function(event, ui) {
var newVal = $(this).val();
var index = $(this).data("index");
mymodel.tableRows()[index].selectedVal(newVal);
}
}).data("index", i);
}
這裏是小提琴https://jsfiddle.net/8rw4ruze/7/
我覺得我得到了它與自定義綁定這裏是 https://jsfiddle.net/8rw4ruze/8/
'mymodel.tableRows()[i]'是'undefined',因爲在加載頁面後i已經是4了。 –
所以我應該爲每個選擇(1,2,3,4)添加一個數據屬性,然後在on change事件中引用select的數據屬性? –
如果我是你,我會使用'knockout'內置'dropDown',你可以訂閱selectedVal。例如:https://jsfiddle.net/8rw4ruze/5/ –