.toggle()
.toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] ) 返回: jQuery
描述: 綁定兩個或多個處理程序綁定到匹配的元素,用來執(zhí)行在交替的點擊。
-
version added: 1.0.toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )
handler(eventObject)第一數(shù)次(奇數(shù))點擊時要執(zhí)行的函數(shù)。
handler(eventObject)第二數(shù)次(偶數(shù))點擊時要執(zhí)行的函數(shù)。
handler(eventObject)更多次點擊時要執(zhí)行的函數(shù)。
.toggle()方法的處理程序綁定一個click事件,這個規(guī)則概述觸發(fā)click這里也適用。
舉例來說,請看下面的HTML:
<div id="target"> Click here </div>

這個事件處理程序可以綁定到<div>:
$('#target').toggle(function() {
alert('First handler for .toggle() called.');
}, function() {
alert('Second handler for .toggle() called.');
});
這樣元素被點擊多次,信息提示:
First handler for .toggle() called.
Second handler for .toggle() called.
First handler for .toggle() called.
Second handler for .toggle() called.
First handler for .toggle() called.
如果提供兩個以上的處理函數(shù),.toggle()將在它們中循環(huán)。例如,如果有三個處理程序,那么第一次點擊,點擊第四,第七點擊后第一個處理程序?qū)⒈徽{(diào)用等等。
The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.
Examples:
Example: Click to toggle highlight on the list item.
<!DOCTYPE html>
<html>
<head>
<style>
ul { margin:10px; list-style:inside circle; font-weight:bold; }
li { cursor:pointer; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<ul>
<li>Go to the store</li>
<li>Pick up dinner</li>
<li>Debug crash</li>
<li>Take a jog</li>
</ul>
<script>
$("li").toggle(
function () {
$(this).css({"list-style-type":"disc", "color":"blue"});
},
function () {
$(this).css({"list-style-type":"disc", "color":"red"});
},
function () {
$(this).css({"list-style-type":"", "color":""});
}
);
</script>
</body>
</html>
Demo:
Example: To toggle a style on table cells:
$("td").toggle(
function () {
$(this).addClass("selected");
},
function () {
$(this).removeClass("selected");
}
);