.toggle()

.toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] ) 官网原E文: jQuery

描述: 绑定两个或多个处理程序绑定到匹配的元素,用来执行在交替的点击。

  • version added: 1.0.toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )

    handler(eventObject)第一数次(奇数)点击时要执行的函数。

    handler(eventObject)第二数次(偶数)点击时要执行的函数。

    handler(eventObject)更多次点击时要执行的函数。

.toggle()方法的处理程序绑定一个click事件,这个规则概述触发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.

如果提供两个以上的处理函数,.toggle()将在它们中循环。例如,如果有三个处理程序,那么第一次点击,点击第四,第七点击后第一个处理程序将被调用等等。

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");
  }
);
jQuery 1.6 API 中文版Clove整理、修订