我有3个使用foreach绑定的列表项。当我点击其中一个时,我希望它切换到'activeClass'。
这是我到目前为止所拥有的!非常感谢您的帮助。
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
<span data-bind="text: name, css: function () { $root.styling(); }, click: function () { $root.toggle();}"> </span>
</li>
</ul>
function AppViewModel() {
var self = this;
self.active = ko.observable(false);
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.styling = ko.computed(function () {
if (self.active() === true) {
return 'activeClass';
}
else {
return '';
}
});
self.toggle = function () {
self.active(!self.active());
}
}
ko.applyBindings(new AppViewModel());
答案 0 :(得分:0)
您需要添加active
作为每个对象的一部分并使其可观察,然后将其传递给函数:JsFiddle
Html部分:
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: name, css: $root.styling($data), click: function () { $root.toggle($data);}"> </span>
</li>
</ul>
ViewModel:
function AppViewModel() {
var self = this;
self.people = ko.observableArray([
{ name: 'Bert', active: ko.observable(false) },
{ name: 'Charles', active: ko.observable(false) },
{ name: 'Denise', active:ko.observable(false) }
]);
self.styling =function (person) {
if (person.active() === true) {
return 'test';
}
else {
return '';
}
};
self.toggle = function (person) {
person.active(!person.active());
}
}
ko.applyBindings(new AppViewModel());