ドキュメント

Events/one

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Events

one( type, [data], fn )

Binds a handler to one or more events to be executed once for each matched element.

The handler is executed only once for each element. Otherwise, the same rules as described in bind() apply. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler should return false.

In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second paramter (and the handler function as the third), see second example.

Possible event values: blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error

Arguments:

typeString
An event type
data (Optional)Object
Additional data passed to the event handler as event.data
fnFunction
A function to bind to the specified event on each of the matched elements.
function callback(eventObject) {
  this; // dom element
}
Examples:

Tie a one-time click to each div.

    var n = 0;
    $("div").one("click", function(){
      var index = $("div").index(this);
      $(this).css({ borderStyle:"inset",
                    cursor:"auto" });
      $("p").text("Div at index #" + index + " clicked." +
                  "  That's " + ++n + " total clicks.");
    });

<!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(){
    
    var n = 0;
    $("div").one("click", function(){
      var index = $("div").index(this);
      $(this).css({ borderStyle:"inset",
                    cursor:"auto" });
      $("p").text("Div at index #" + index + " clicked." +
                  "  That's " + ++n + " total clicks.");
    });

  });
  </script>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
        background:green; border:10px outset; 
        cursor:pointer; }
  p { color:red; margin:0; clear:left; }
  </style>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <p>Click a green square...</p>
</body>
</html>

To display the text of all paragraphs in an alert box the first time each of them is clicked:

$("p").one("click", function(){
  alert( $(this).text() );
});

NameType