我在以下 jsfiddle 中重新创建了问题:
HTML
<h2>Edit Person Here</h2>
<div data-bind="with: EditPerson">
<h3 data-bind="html: Name"></h3>
<!--Uncomment line below to generate binding error. -->
<!--<select data-bind="options:$parent.IceCreams, optionsText: Name, optionsValue: Id"></select>-->
</div>
<h2>List of People</h2>
<div data-bind="foreach: People">
<div data-bind="click: $parent.SelectPerson">
<h3 data-bind="html: Name"></h3>
Favorite IceCream: <span data-bind="html: FavoriteIceCream().Name"></span>
</div>
</div>
Javascript
function ViewModel() {
var self = this;
self.IceCreams = ko.observableArray([
new IceCream(1, "Chocolate"),
new IceCream(2, "Vanilla"),
new IceCream(3, "Mint")
]);
self.EditPerson = ko.observable(new Person("", self.IceCreams()[0]));
self.People = ko.observableArray([
new Person("Joe", self.IceCreams()[2]),
new Person("Sue", self.IceCreams()[0]),
new Person("Carl", self.IceCreams()[1])
]);
self.SelectPerson = function(person){
self.EditPerson(person);
}
}
function Person(Name, FavoriteIceCream){
var self = this;
self.Name = ko.observable(Name);
self.FavoriteIceCream = ko.observable(FavoriteIceCream);
}
function IceCream(Id, Name){
var self = this;
self.Id = Id;
self.Name = Name;
}
ko.applyBindings(new ViewModel());
当您从列表中选择一个人时,他们的名字将出现在上方。我想添加一个下拉菜单,让您可以选择所选人员最喜欢的冰淇淋。我在 html 中注释掉了我希望工作的内容。
但是,似乎不是使用选项参数对象的上下文,而是使用父 div 的 with 参数的上下文。
如何编写选择标签以使绑定起作用?