我正在尝试将dropdown与可观察数组绑定,并根据条件设置所选项,但所选值未更新。
相同的代码是:
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
var viewModel = function(){
var self= this;
self.test = ko.observable('a'),
self.selectedItem = ko.computed(function () {
var tempreview = self.test();
if (tempreview === "a") {
return ko.observable("2");
}
else
return ko.observable("3");
}),
self.items = ko.observableArray([new Item(3, "")])
};
var vm = new viewModel();
vm.items([new Item(1, "pencil"),
new Item(2, "pen"),
new Item(3, "marker"),
new Item(4, "crayon")
]);
ko.applyBindings(vm);
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value:selectedItem"></select>
<div data-bind="text: selectedItem"></div>
Jsfiddle链接是://jsfiddle.net/sajesh1985/c7MCh/2 /
谢谢, Sajesh
答案 0 :(得分:1)
在selectedItem
计算中,只需返回&#39; 2&#39;或者&#39; 3&#39;,而不是可观察的:
self.selectedItem = ko.computed(function () {
var tempreview = self.test();
if (tempreview === "a") {
return '2';
}
else
return '3'
}),