Javascript 使用knockoutjs+;推特引导
我试图跟踪视图模型中选定的选项卡,但似乎无法使其正常工作 在以下代码中,当您单击选项卡时,标题将正确更新,但不会显示选项卡的内容。如果删除Javascript 使用knockoutjs+;推特引导,javascript,html,twitter-bootstrap,knockout.js,Javascript,Html,Twitter Bootstrap,Knockout.js,我试图跟踪视图模型中选定的选项卡,但似乎无法使其正常工作 在以下代码中,当您单击选项卡时,标题将正确更新,但不会显示选项卡的内容。如果删除,请单击:$parent。选择Section,则会显示内容,但标题不会更新 现在,如果您从li中删除data bind=“css:{active:selected}”,那么当您单击选项卡时,它似乎起作用,但选择第二个选项卡的按钮不起作用 我怎样才能做到这一点 见: HTML: 有几种方法可以处理这个问题,可以使用bootstrap的JS,也可以让Knockou
,请单击:$parent。选择Section
,则会显示内容,但标题不会更新
现在,如果您从li
中删除data bind=“css:{active:selected}”
,那么当您单击选项卡时,它似乎起作用,但选择第二个选项卡的按钮不起作用
我怎样才能做到这一点
见:
HTML:
有几种方法可以处理这个问题,可以使用bootstrap的JS,也可以让Knockout添加/删除
active
类
为了使用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>
-
此处示例:
您可以使用多种变体,但我认为这是一种简单的方法
下面是一个调整,活动选项卡将节名称用作模板:
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>