我有一系列限制,以及启用/禁用限制的复选框。但是复选框不起作用
function Limit(start, end)
{
var that = this;
this.start = start;
this.end = end;
this.label = ko.computed(function(){
return that.start + ' - ' + that.end;
});
}
function ViewModel()
{
var that = this;
this.limits = [new Limit(1,2), new Limit(3,4), new Limit(4,5)];
this.activeLimit = ko.observable(that.limits[0]);
this.changeActiveLimit = function(limit)
{
that.activeLimit(limit);
}
}
ko.applyBindings(new ViewModel());
我的HTML
<div data-bind="foreach: {data: limits, as: 'limit'}">
<input type="checkbox" data-bind="click: $root.changeActiveLimit, checked: limit.label == $root.activeLimit().label"/>
<span data-bind="text: limit.label"/>
</div>
答案 0 :(得分:13)
如果你修改你的viewModel,它将起作用
function ViewModel()
{
var that = this;
this.limits = [new Limit(1,2), new Limit(3,4), new Limit(4,5)];
this.activeLimit = ko.observable(that.limits[0]);
this.changeActiveLimit = function(limit)
{
that.activeLimit(limit);
return true;
}
}
return true 是这里的关键部分。
答案 1 :(得分:11)
关键是在点击处理函数结束时返回true; !这会正确更新UI。