视图模型:
function Specialization(id, name) {
var self = this;
self.id = id;
self.name = name;
}
function ObservableSpecialization() {
var self = this;
self.availableItem = ko.observable();
}
function ViewModel() {
var self = this;
self.specializations = ko.observableArray([]);
self.availableSpecializations = [];
self.addSpecialization = function () {
self.specializations.push(new Specialization());
}
self.removeSpecialization = function (specialization) {
self.specializations.remove(specialization)
}
}
文件载入:
$(document).ready(function () {
var model = new ViewModel();
var temp = [];
$.each(window.availableSpecializations, function (i, item) {
var specialization = new Specialization(item.ID, item.Name);
model.availableSpecializations.push(specialization);
temp.push(item.ID);
});
$.each(window.userSpecializations, function (i, item) {
var idx = temp.indexOf(item.ID);
if (idx != -1) {
var available = model.availableSpecializations[idx];
var specialization = new ObservableSpecialization();
specialization.availableItem = available;
model.specializations.push(specialization);
}
});
ko.applyBindings(model);
});
<select>
代码段:<tbody data-bind="foreach: specializations">
<tr>
<td>
<select name="Specializations" data-bind="options: $root.availableSpecializations, value: 'availableItem', optionsText: 'name'">
</select>
</td>
结果:
正如您在下面看到的那样,所有值始终设置为列表中的第一项。我想ID不会以某种方式绑定到所选项目...我在哪里出错?
最佳答案
有两个问题:
首先,specialization.availableItem
是可观察的,因此应分配一个函数调用:specialization.availableItem(available)
其次,在绑定字符串中,您有value: 'availableItem'
,它仅将选择值设置为字符串“ availableItem”。应该没有引号:value: availableItem
这是2个修复的小提琴:jsfiddle
关于javascript - knockout JS:在“选择”标签中显示不正确的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11270970/