【发布时间】:2014-06-19 09:51:59
【问题描述】:
我有一个带有多个属性的选择。对于选择中的每个选项,我想要设置标题属性(显示工具提示)。我还想将选定的选项作为对象数组检索。除了所选选项不返回对象数组而是 valueTexts 数组这一事实之外,我设法得到了我想要的东西。我不知道如何在该数组中获取对象。
这是我目前得到的代码:
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:
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/
我需要添加或更改什么以使数组 selectedOptions 包含对象而不是字符串?
【问题讨论】:
-
您不需要为此使用 foreach。看看here