Примеры для jQuery .off()


Add and remove event handlers on the colored button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>off demo</title>
<style>
button {
margin: 5px;
}
button#theone {
color: red;
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="theone">Does nothing...</button>
<button id="bind">Add Click</button>
<button id="unbind">Remove Click</button>
<div style="display:none;">Click!</div>
<script>
function flash() {
$( "div" ).show().fadeOut( "slow" );
}
$( "#bind" ).click(function() {
$( "body" )
.on( "click", "#theone", flash )
.find( "#theone" )
.text( "Can Click!" );
});
$( "#unbind" ).click(function() {
$( "body" )
.off( "click", "#theone", flash )
.find( "#theone" )
.text( "Does nothing..." );
});
</script>
</body>
</html>

Демонстрация:

Remove all event handlers from all paragraphs:

1
$( "p" ).off();

Remove all delegated click handlers from all paragraphs:

1
$( "p" ).off( "click", "**" );

Remove just one previously bound handler by passing it as the third argument:

1
2
3
4
5
6
7
8
9
var foo = function() {
// Code to handle some kind of event
};
// ... Now foo will be called when paragraphs are clicked ...
$( "body" ).on( "click", "p", foo );
// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );

Unbind all delegated event handlers by their namespace:

1
2
3
4
5
6
7
8
9
10
11
var validate = function() {
// Code to validate form entries
};
// Delegate events under the ".validator" namespace
$( "form" ).on( "click.validator", "button", validate );
$( "form" ).on( "keypress.validator", "input[type='text']", validate );
// Remove event handlers in the ".validator" namespace
$( "form" ).off( ".validator" );