Suppose that we wanted to be able to hide our style switcher when it is not needed. One convenient way to hide advanced features is to make them collapsible. We will allow one click on the label to hide the buttons, leaving the label alone. Another click on the label will restore the buttons. We need another class to handle the hidden buttons, as follows:
.hidden {display: none;}
假如我们想要在风格切换器不需要的时候隐藏他。一个隐藏高级特点的便利的方法就是让他们可折叠。我们将用户点击标签的时候隐藏按钮,而只留下标签。再见一下标签的时候,按钮将会重新出现。我们需要另一个类去处理隐藏的按钮,如下:
.hidden {display: none;}
We could implement this feature by storing the current state of the buttons in a variable, and checking its value each time the label is clicked to know whether to add or remove the hidden class on the buttons. We could also directly check for the presence of the class on a button, and use this information to decide what to do. Instead, jQuery provides the .toggle()method, which performs this housekeeping task for us.
我们可以通过一个变量存储按钮当时的状态来实现这个特点,然后在每一次点击标签的时候检查一下这个变量的值来确定是否要添加还是移除按钮上的隐藏的类。我们也可以直接检查当时这个按钮上面的类,然后使用这个信息来决定我们要去做什么。但是,jquery提供了一个.toggle()方法,他可以帮我们完成这个内部事件。
Toggle effect
There are in fact two .toggle()methods defined by jQuery. For information on the effect method of this name (which is distinguished by different argument types), see: http://api.jquery.com/toggle/
$(document).ready(function() {
$('#switcher h3').toggle(function() {
$('#switcher button').addClass('hidden');
}, function() {
$('#switcher button').removeClass('hidden');
});
});
.toggle()方法需要两个或者更多的参数,每一个都是函数。第一次点击将会调用第一个函数,第二次点击将会调用第二个函数等等。一旦每一个函数都被调用了以后,将会从第一个函数重新开始循环。使用.toggle()方法,我们可以非常简单的实现我们的可折叠的风格切换器。代码同上
After the first click, the buttons are all hidden:
And a second click returns them to visibility:
在第一次点击后,所有的按钮都被隐藏了:
在第二次点击后他们又重新可见了:
Once again, we rely on implicit iteration; this time, to hide all the buttons in one fell swoop without requiring an enclosing element.
这一次我们又是使用了隐式迭代的特点。这时候隐藏所有的元素一下子就实现了,而不用请求内部的元素。
For this specific case, jQuery provides another mechanism for the collapsing we are performing. We can use the .toggleClass()method to automatically check for the presence of the class before applying or removing it:
$(document).ready(function() {
$('#switcher h3').click(function() {
$('#switcher button').toggleClass('hidden');
});
});
在这种特殊的场景下,jquery提供了另外一种机制用来实现我们需要的折叠。我们使用.toggleClass()来自动在添加或者移除之前检查当前类:
$(document).ready(function() {
$('#switcher h3').click(function() {
$('#switcher button').toggleClass('hidden');
});
});
In this case, .toggleClass()is probably the more elegant solution, but .toggle()is, in general, a versatile way to perform two or more different actions in alternation.
在这种场景下,.toggleClass()可能是最又优雅的解决方案了,但是.toggle()事实是表现一连串串联行为的通用的方法。