2

当鼠标悬停在特定选项上时,我想根据选择值显示标题(步行、跑步、谈话) 。

这是我的小提琴

这是淘汰赛中的错误(或)我做错了吗?

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());

任何帮助都是可观的

4

2 回答 2

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为当前选定的元素显示 a ,您将需要一个计算的 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

于 2013-02-25T10:11:28.497 回答
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 : "" ;
});
于 2013-10-24T18:56:19.777 回答