我正在尝试在select元素上使用值绑定,如该小提琴中所述: jsfiddle /MikeEast/nM6dd/2/
I am trying to use the value binding on the select element, as described in this fiddle: jsfiddle/MikeEast/nM6dd/2/
但是,我似乎无法设置所选选项(值绑定).
However, I cannot seem to be able to set the selected option (value binding).
我知道我可以使用optionsValue绑定,但这会使该值成为字符串,而不是一个对象,这是不可取的.如果那是唯一的方法,我将如何确保将所选的选项写回到视图模型中?
I know I can use the optionsValue binding, but that makes the value a string instead of an object which is not preferable. If that is the only way to go, how would I do to ensure that the selected option is written back to the view model?
谢谢!
推荐答案以下是解决方案.您必须将属性optionsValue: 'id'添加到数据绑定中. 您还必须在viewModel中放置一个返回所选对象的函数.
Here is the solution. You have to add the attribute optionsValue: 'id' to the data-bind. You also have to put a function in you viewModel that returns the selected object.
var viewModel = function() { this.items = ko.observableArray([ { id: 1, name: "Apple" }, { id: 2, name: "Orange"}, { id: 3, name: "Banana"} ]); this.selectedItemId = ko.observable(3); this.selectedItem = function() { var self = this; return ko.utils.arrayFirst(this.items(), function(item) { return self.selectedItemId() == item.id; }); }.bind(this); }; var vm = new viewModel(); ko.applyBindings(vm);
<script src="cdnjs.cloudflare/ajax/libs/knockout/1.2.1/knockout-min.js"></script> <select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedItemId"></select> <span data-bind="text: selectedItem().name"></span>
干杯!
更多推荐
具有复杂类型时,KnockoutJs中的值绑定无法进行选择
发布评论