Knockout 以类似于以下方式将值包装在计算函数中:
Input: "yourClassName": whateverYouPutIn
Output: "yourClassName": ko.computed(function() { return whateverYouPutIn; })
在您的情况下,您输入了一个函数,这将导致设置 active 类的“真实”值。您可以通过以下方式解决此问题:
选项 1(快速):不要将其包装在函数中
<li data-bind="css: {
'active': document.title.indexOf('Home') > -1
}"></li>
选项2(不推荐):修正错字(funciton)并调用函数
<li data-bind="css: {
'active': (function() {
return document.title.indexOf('Home') > -1;
}())
}"></li>
选项 3:将这些类型的属性添加到您的视图模型中
var vm = {
// set when VM is initialized
isActive: document.title.indexOf("Home"),
// if you want to check the title during data-binding
isActiveDuringBind: function() {
return document.title.indexOf("Home");
}
}
任一个
<li data-bind="css: {'active': isActive }"></li>
或
<li data-bind="css: {'active': isActiveDuringBind() }"></li>
请注意,在自定义绑定之外使用 DOM api 被认为是“不好的做法”......但在这种情况下,我想你可以侥幸逃脱......
请注意,由于没有使用可观察值,因此当您更改 document.title 时,您的类不会切换。