具有复杂类型时,KnockoutJs中的值绑定无法进行选择

编程入门 行业动态 更新时间:2024-10-12 03:23:06
本文介绍了具有复杂类型时,KnockoutJs中的值绑定无法进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在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中的值绑定无法进行选择

本文发布于:2023-11-16 15:25:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   类型   KnockoutJs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!