我有:
<select name="test" id="test" class=""
data-bind="
options: myArray,
value: idSelected,
optionsText: 'name',
optionsValue: 'id',
optionsCaption: 'All'">
我不想只有id,我想在列表中选择一个项目时在对象中设置我的数组的id和名称。样品:
我想要这个结果:
idSelected = {id:1, name:'Test'};
答案 0 :(得分:3)
只需从绑定中删除optionsValue
即可。这会将idSelected
设置为observableArray
的对象而不是字符串(documentation)
这是一个工作片段:
var viewModel = function() {
var self = this;
self.myArray = ko.observableArray([{
id: 1,
name: 'Test 1'
}, {
id: 2,
name: 'Test 2'
}]);
self.idSelected = ko.observable();
self.idSelected.subscribe((selected) => {
console.log(self.idSelected());
});
}
ko.applyBindings(new viewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select name="test" id="test" class="" data-bind="
options: myArray,
value: idSelected,
optionsText: 'name',
optionsCaption: 'All'">
&#13;