Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation. The second two forms, introduced in jQuery 1.7, are identical to .on() except that the handler is removed after the first time the event occurs at the delegated element, whether the selector matched anything or not. For example:
$( "#foo" ).one( "click", function() {
alert( "This will be displayed only once." );
});
$( "body" ).one( "click", "#foo", function() {
alert( "This displays if #foo is the first thing clicked in the body." );
});
After the code is executed, a click on the element with ID foo will display the alert. Subsequent clicks will do nothing. This code is equivalent to:
$( "#foo" ).on( "click", function( event ) {
alert( "This will be displayed only once." );
$( this ).off( event );
});
In other words, explicitly calling .off() from within a regularly-bound handler has exactly the same effect.
If the first argument contains more than one space-separated event types, the event handler is called once for each event type.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<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>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<p>Click a green square...</p>
<script>
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>
</body>
</html>
$( "p" ).one( "click", function() {
alert( $( this ).text() );
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="count">0</div>
<div class="target">Hover/click me</div>
<script>
var n = 0;
$(".target").one("click mouseenter", function() {
$(".count").html(++n);
});
</script>
</body>
</html>