我希望在特定选项上使用mouseOver时根据选择值显示标题(步行,跑步,谈话)。
这是淘汰赛中的错误(或)我做错了吗?
HTML: -
<select data-bind="value: activityId,optionsValue: 'id', optionsText: 'name', options: activityArray,optionsCaption:'Select',attr: {title:'name'}">
脚本
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
var self = this;
self.activityId = ko.observable("");
self.activityArray = ko.observableArray();
self.activityArray.push(new Activity(1,'walk'));
self.activityArray.push(new Activity(2,'run'));
self.activityArray.push(new Activity(3,'talk'));
}
function Activity(id,name){
this.id = id;
this.name = name;
};
// Activates knockout.js
ko.applyBindings(new AppViewModel());
任何帮助都很明显
答案 0 :(得分:3)
如果您希望在生成的options
元素上有其他属性,则无法使用options
绑定,您必须使用foreach
<select data-bind="value: activityId">
<option>Select</option>
<!-- ko foreach: activityArray -->
<option data-bind="value: id, text: name, attr: {title: name}"></option>
<!-- /ko -->
</select>
如果你想为当前选择的元素显示一个title
,你需要一个计算的observable来计算activityId
的标题:
self.selectedActivity = ko.computed(function () {
var selected = ko.utils.arrayFirst(self.activityArray(), function (item) {
return item.id == self.activityId()
});
if (selected)
return selected.name;
});
然后您可以在选择中使用此selectedActivity
:
<select data-bind="value: activityId, attr: {title: selectedActivity}">
演示JSFiddle。
答案 1 :(得分:3)
另一种解决方案可能是:http://jsfiddle.net/un2qh/3/
HTML:
<select data-bind="options: activityArray, optionsText: 'name',
value: selectedActivity, attr: {title: activityTitle},
optionsCaption: 'Choose...', optionsAfterRender: setOptionTitle">
</select>
JS(标题的主要计算属性):
self.activityTitle = ko.computed(function () {
return self.selectedActivity() ? self.selectedActivity().name : "" ;
});