toggle

UK[ˈtɒgl] US[ˈtɑ:gl]

n.Stick button; lasso button; conversion key; switch key

v.Switch

jquery toggle() method syntax

Function:The toggle() method is used to bind two or more event handler functions to respond to the click event of the selected element in turn. This method can also be used to switch the hide() and show() methods of the selected element.

Bind two or more functions to the toggle event: When the specified element is clicked, switch between two or more functions in turn. If more than two functions are specified, the toggle() method will toggle all functions. For example, if there are three functions, the first click will call the first function, the second click will call the second function, and the third click will call the third function. The fourth click calls the first function again, and so on.

Syntax: $(selector).toggle(function1(),function2(),functionN(),...)

Parameters :

Parameter Description
function1() Required. Specifies a function to run when the element is clicked every even number of times.
function2() Required. Specifies a function to be run every odd number of times the element is clicked.
functionN(),... Optional. Specify other functions that need to be switched.


Hide() and Show():
Check whether each element is visible. If the element is hidden, run show(). If the element is visible, the element hide(). This creates a switching effect.

Syntax: $(selector).toggle(speed,callback)

Parameters:

ParameterDescription
speed Optional. Specifies the speed of hide/show effects. The default is "0". Possible values: milliseconds (e.g. 1500) "slow" "normal" "fast"
callbackOptional. Function executed when the toggle() method completes.


Show or hide elements:
Specifies whether to only display or hide all matching elements.

Syntax: $(selector).toggle(switch)

##Parameters:

ParameterDescriptionswitch Required. A Boolean value that specifies whether toggle() should only show or hide all selected elements. true - show the element false - hide the element

jquery toggle() method example

<html>
<head>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").toggle(function(){
    $("body").css("background-color","green");},
    function(){
    $("body").css("background-color","red");},
    function(){
    $("body").css("background-color","yellow");}
  );
});
</script>
</head>
<body>
<button>请点击这里,来切换不同的背景颜色</button>
</body>
</html>
Run instance »

Click the "Run instance" button to view the online instance