gpt4 book ai didi

javascript - knockout JS : Showing incorrect values in "select" tag

转载 作者:行者123 更新时间:2023-11-30 18:24:25 25 4
gpt4 key购买 nike

View 模型:

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 未以某种方式绑定(bind)到所选项目...我哪里出错了?

enter image description here

最佳答案

有两个问题:首先,specialization.availableItem 是一个可观察对象,因此应该通过函数调用来分配:specialization.availableItem(available)

其次,在绑定(bind)字符串中,您有 value: 'availableItem',它只是将选择值设置为字符串 'availableItem'。应该没有引号:value: availableItem

这是一个包含 2 个修复的 fiddle :jsfiddle

关于javascript - knockout JS : Showing incorrect values in "select" tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11270970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com