knockout multiselect selectedOptions包含值而不是对象 [英] knockout multiselect selectedOptions contains values instead of objects
问题描述
我有一个属性为select的select。对于select中的每个选项,我想要title属性集(显示工具提示)。我还想将所选选项检索为对象数组。我设法得到了我想要的东西,除了选择的选项不返回一个对象数组但是返回一个valueTexts数组的事实。我无法弄清楚如何在该数组中获取对象。
I have a select with the attribute multiple. For each option in the select I want the title attribute set (which shows a tooltip). I also want to retrieve the selected options as an array of objects. I managed to get what I want except for the fact that the selected options doesnt return an array of objects but an array of valueTexts. I can't figure out how I get objects in that array.
这是我到目前为止的代码:
This is the code I got so far:
HTML:
<select multiple style="width: 150px;" size=15
data-bind="foreach: options, selectedOptions: selectedOptions">
<option data-bind="text: Name, attr: { 'title': Name}"></option>
</select><br />
<button data-bind="click: showSelectedOptions">Show selection</button>
Javascript:
Javascript:
function Option(id, name){
var self = this;
self.Id = id;
self.Name = name;
}
function ViewModel(){
var self = this;
self.options = ko.observableArray([
new Option(0, "NormalText"),
new Option(1, "AnotherText"),
new Option(2, "WaaaaaaaaaaaaaaaayTooLongText")
]);
self.selectedOptions = ko.observableArray([]);
self.showSelectedOptions = function(){
alert(self.selectedOptions());
//what I would like to have:
//if (self.selectedOptions().length > 0)
// alert(self.selectedOptions()[0].Name);
}
}
ko.applyBindings(new ViewModel());
以及用于演示的小提琴链接: http://jsfiddle.net/c63Bb/1/
And the fiddle link for demonstration: http://jsfiddle.net/c63Bb/1/
我需要添加或更改内容数组selectedOptions包含对象而不是字符串?
What do I need to add or change so the array selectedOptions contains objects instead of strings?
推荐答案
试试这样的html
<select
data-bind="
options: options,
selectedOptions : selectedOptions,
optionsText: 'Name',
optionsCaption: 'Choose...'
"
size="5" multiple="true"></select>
请参阅控制台输出
要向选项添加属性,您需要使用 optionsAfterRender
。
这仅在3.1.0版中可用。我注意到你的小提琴正在使用3.0.0。
To add attributes to option you need to use optionsAfterRender
.
This is available only in version 3.1.0. I noticed your fiddle is using 3.0.0.
<select
data-bind="
options: options,
selectedOptions : selectedOptions,
optionsText: 'Name',
optionsAfterRender: $root.setTitle
"
size="5" multiple="true"></select><br />
<button data-bind="click: showSelectedOptions">Show selection</button>
并创建一个函数
self.setTitle = function(option, item) {
option.title = item.Name
}
参考
见注2
Reference
See Note 2这篇关于knockout multiselect selectedOptions包含值而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!