我看了这个其他的问题,但不能让我的选择框才能正常工作: Binding initial/default value of dropdown (select) list如何预选择一个选项下拉淘汰赛JS
我已经得到了下面的游戏对象:
function Game(visitingTeamDetails, homeTeamDetails, game) {
if (arguments.length > 0) {
this.VisitingTeamDetails = visitingTeamDetails;
this.HomeTeamDetails = homeTeamDetails;
this.GameId = ko.observable(game.GameId);
this.HomeTeamName = ko.observable(game.HomeTeamName);
this.VisitingTeamName = ko.observable(game.VisitingTeamName);
this.SportTypeName = ko.observable(game.SportTypeName);
this.HomeAccountName = ko.observable(game.HomeAccountName);
this.VisitingAccountName = ko.observable(game.VisitingAccountName);
this.GameDateString = ko.observable(game.GameDateString);
this.GameTimeString = ko.observable(game.GameTimeString);
this.AvailableSportTypes = ko.observableArray(game.Sports);
this.sportTypeFunction = function() {
for (sportType in this.AvailableSportTypes()) {
if (this.AvailableSportTypes()[sportType].Name == this.SportTypeName()) {
return this.AvailableSportTypes()[sportType];
}
}
return null;
};
this.SportType = ko.observable(game.SportType);
}
}
SportType与Name
和SportTypeId
的对象。
我有以下模板:
<td rowspan="3"><select data-bind="options: AvailableSportTypes, value: SportType, optionsText:'Name', optionsCaption: 'Choose...'" class="sportType"></select></td>
AvailableSportTypes
是SportType
列表。
该列表与下拉列表中的SportTypes名称一起提供,但我无法将初始选择设置为SportType
。我写了sportTypeFunction
向我表明自己数据传入正确,并且它会选择正确的值,但在下拉列表中更改我的选择不会更新SportType。
我确定我做错了什么。任何人都看到它?
感谢
是'SportType'假设为对象?如果是这样,那么'game.SportType'是否被引用到'game.AvailableSportTypes'数组中的一个项目中?基本上两个对象是不相等的,除非它们实际上是对同一个对象的引用。 'var a = {name:“test”},b = {name:“test”};警报(a === b); //假' –
优秀点。这将解释行为。所以我需要编写自己的比较运算符?或者我可以在某处重载原型函数? –
@RP Niemeyer - 我实际上再次调用了sportTypeFunction来设置我的初始值,并且一切正常,包括更改选项。不知道我以前做错了什么。感谢您指出对象平等问题。有什么聪明的方法呢?我的功能感觉很不好。 –