剔除多选 selectedOptions 包含值而不是对象 [英] knockout multiselect selectedOptions contains values instead of objects
问题描述
我有一个属性为 multiple 的选择.对于选择中的每个选项,我想要设置标题属性(显示工具提示).我还想将选定的选项作为对象数组进行检索.我设法得到了我想要的东西,除了选定的选项不返回对象数组而是返回 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
Try your html like this
<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
这篇关于剔除多选 selectedOptions 包含值而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!