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


Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$( "body" ).delegate( "p", "click", function() {
$( this ).after( "<p>Another paragraph!</p>" );
});
</script>
</body>
</html>

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

To display each paragraph's text in an alert box whenever it is clicked:

1
2
3
$( "body" ).delegate( "p", "click", function() {
alert( $( this ).text() );
});

To cancel a default action and prevent it from bubbling up, return false:

1
2
3
$( "body" ).delegate( "a", "click", function() {
return false;
});

To cancel only the default action by using the preventDefault method.

1
2
3
$( "body" ).delegate( "a", "click", function( event ) {
event.preventDefault();
});

Can bind custom events too.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "body" ).delegate( "p", "myCustomEvent", function( e, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent" );
});
</script>
</body>
</html>

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