ドキュメント

Events/toggle

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Events

toggle( fn, fn2, [fn3,fn4,...] )

Toggle among two or more function calls every other click.

Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired, and so on. All subsequent clicks continue to rotate through the functions.

Use unbind("click") to remove the toggle event.

Arguments:

fnFunction
The function to execute.
function callback(eventObject) {
  this; // dom element
}
fn2Function
The function to execute.
function callback(eventObject) {
  this; // dom element
}
fn3,fn4,... (Optional)Function
The function to execute.
function callback(eventObject) {
  this; // dom element
}
Examples:

Click to toggle highlight on the list item.

    $("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":""});
      }
    );

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("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>
  <style>
  ul { margin:10px; list-style:inside circle; font-weight:bold; }
  li { cursor:pointer; }
  </style>
</head>
<body>
  <ul>
    <li>Go to the store</li>
    <li>Pick up dinner</li>
    <li>Debug crash</li>
    <li>Take a jog</li>
  </ul>
</body>
</html>

To toggle a style on table cells:

$("td").toggle(
  function () {
    $(this).addClass("selected");
  },
  function () {
    $(this).removeClass("selected");
  }
);

NameType