在下面的select
中,我绑定(bind)了一个可观察数组。
<select id="selectProtocols" data-bind="options: optionsAvailable, optionsCaption:'Selecione...', optionsText: 'SimpleDescription', optionsValue:'???'"></select>
我相信很容易看出每个选项的文本都是一个属性“SimpleDescription”,效果很好。我现在需要的是 select
的 value
是元素本身!
我怎样才能做到这一点?
最佳答案
分配$data
至optionsValue
这里没有意义,你必须阅读什么optionsValue
确实[1]。它基本上只是设置 value
<option>
的属性您的 <select>
下的元素。所以你不能将其设置为正在选择的JS对象,只能将其设置为文本。
<select data-bind="
options: optionsAvailable,
optionsCaption: 'Selecione...',
optionsText: 'SimpleDescription',
optionsValue: 'SomeOtherPropertyThatEvaluatesToText',
value: selectedOption"></select>
value
绑定(bind)应该接收一个将被设置为所选 JS 对象的可观察对象。并且,如果您愿意,您可以给 optionsValue
一个函数,它接受这个 JS 对象并将其转换为文本,如下所示:
<select data-bind="
options: optionsAvailable,
optionsCaption: 'Selecione...',
optionsText: 'SimpleDescription',
optionsValue: JSON.stringify,
value: selectedOption"></select>
这是一个可以使用的示例 fiddle :http://jsfiddle.net/43t9dzxt/1/
[1] http://knockoutjs.com/documentation/options-binding.html
关于javascript - Knockout -> 将元素绑定(bind)到 Select 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31141342/