javascript 淘汰赛:如何在单击按钮时切换多个 div 的可见性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11561756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout: How do I toggle visibility of multiple divs on button click?
提问by the-petrolhead
I want to toggle visibility of multiple divs using knockout. Below is the rough idea of my problem -
我想切换使用淘汰赛多个div的可见性。以下是我的问题的粗略想法 -
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<div> Div 1 </div>
<div> Div 2 </div>
<div> Div 3 </div>
By default, 'Div 1' should be visible.
默认情况下,“Div 1”应该是可见的。
When I click individual buttons it should display only the related divs based on the buttons clicked.
当我点击各个按钮应该只显示基于点击的按钮相关的div。
I have gone through the Knockout live examples but not getting how to do this efficiently.
我已经通过基因敲除活生生的实例走了,但没有得到如何有效地做到这一点。
Please help!
请帮忙!
回答by Paul Alan Taylor
The following will do a job for you. It's not ideal, but should give you a platform to work on.
以下将为您做一份工作。这并不理想,但应该为您提供一个工作平台。
First, everything in Knockout is tied to a view model. You want to be able to control the visibility of 3 divs, so here's a view model which might suit. Like I said, not perfect :)
首先,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());
}
}
You'll need to change your markup to:-
您需要将标记更改为:-
<!-- 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>
Couple of things to note here. First, I've added the typeattribute. Without it, the default behaviour of the button will be to try and submit your form.
这里有几点需要注意。首先,我添加了type属性。没有它,按钮的默认行为将是尝试提交您的表单。
Tying it all up:-
把这一切捆绑起来:-
// Create view model
var vm = new buttonVm();
ko.applyBindings(vm);