有几种方法可以处理这个问题,要么使用 bootstrap 的 JS,要么让 Knockout 添加/删除active
class.
为了仅使用 Knockout 来做到这一点,这里有一种解决方案,其中部分本身有一个计算来确定它当前是否被选择。
var Section = function (name, selected) {
this.name = name;
this.isSelected = ko.computed(function() {
return this === selected();
}, this);
}
var ViewModel = function () {
var self = this;
self.selectedSection = ko.observable();
self.sections = ko.observableArray([
new Section('One', self.selectedSection),
new Section('Two', self.selectedSection),
new Section('Three', self.selectedSection)
]);
//inialize to the first section
self.selectedSection(self.sections()[0]);
}
ko.applyBindings(new ViewModel());
标记看起来像:
<div class="tabbable">
<ul class="nav nav-tabs" data-bind="foreach: sections">
<li data-bind="css: { active: isSelected }">
<a href="#" data-bind="click: $parent.selectedSection">
<span data-bind="text: name" />
</a>
</li>
</ul>
<div class="tab-content" data-bind="foreach: sections">
<div class="tab-pane" data-bind="css: { active: isSelected }">
<span data-bind="text: 'In section: ' + name" />
</div>
</div>
</div>
示例在这里:http://jsfiddle.net/rniemeyer/cGMTV/ http://jsfiddle.net/rniemeyer/cGMTV/
您可以使用多种变体,但我认为这是一种简单的方法。
这是一个调整,其中活动选项卡使用部分名称作为模板:http://jsfiddle.net/rniemeyer/wbtvM/ http://jsfiddle.net/rniemeyer/wbtvM/