以下将为您完成工作。这并不理想,但应该给你一个工作的平台。
首先,Knockout 中的所有内容都与视图模型相关联。您希望能够控制 3 个 div 的可见性,所以这里有一个可能适合的视图模型。就像我说的,不完美:)
var buttonVm = new function(){
var self = this;
// Flags for visibility
// Set first to true to cover your "first should be open" req
self.button1Visible = ko.observable(true);
self.button2Visible = ko.observable(false);
self.button3Visible = ko.observable(false);
self.toggle1 = function(){
self.button1Visible(!self.button1Visible());
}
self.toggle2 = function(){
self.button2Visible(!self.button2Visible());
}
self.toggle3 = function(){
self.button3Visible(!self.button3Visible());
}
}
您需要将标记更改为:-
<!-- events here. When clicked call the referenced function -->
<button type="button" data-bind="click: toggle1">Button 1</button>
<button type="button" data-bind="click: toggle2">Button 2</button>
<button type="button" data-bind="click: toggle3">Button 3</button>
<!-- Visibility set here -->
<div data-bind="visible: button1Visible"> Div 1 </div>
<div data-bind="visible: button2Visible"> Div 2 </div>
<div data-bind="visible: button3Visible"> Div 3 </div>
这里有几点需要注意。首先,我添加了type属性。没有它,按钮的默认行为将是尝试提交表单。
把它绑起来:-
// Create view model
var vm = new buttonVm();
ko.applyBindings(vm);