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


Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>bind 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 or double click here.</p>
<span></span>
<script>
$( "p" ).bind( "click", function( event ) {
var str = "( " + event.pageX + ", " + event.pageY + " )";
$( "span" ).text( "Click happened! " + str );
});
$( "p" ).bind( "dblclick", function() {
$( "span" ).text( "Double-click happened in " + this.nodeName );
});
$( "p" ).bind( "mouseenter mouseleave", function( event ) {
$( this ).toggleClass( "over" );
});
</script>
</body>
</html>

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

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

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

You can pass some extra data before the event handler:

1
2
3
4
5
6
function handler( event ) {
alert( event.data.foo );
}
$( "p" ).bind( "click", {
foo: "bar"
}, handler );

Cancel a default action and prevent it from bubbling up by returning false:

1
2
3
$( "form" ).bind( "submit", function() {
return false;
})

Cancel only the default action by using the .preventDefault() method.

1
2
3
$( "form" ).bind( "submit", function( event ) {
event.preventDefault();
});

Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.

1
2
3
$( "form" ).bind( "submit", function( event ) {
event.stopPropagation();
});

Bind custom events.

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>bind 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>
$( "p" ).bind( "myCustomEvent", function( e, myName, myValue ) {
$( this ).text( myName + ", hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent", [ "John" ] );
});
</script>
</body>
</html>

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

Bind multiple events simultaneously.

1
2
3
4
5
6
7
8
9
10
11
$( "div.test" ).bind({
click: function() {
$( this ).addClass( "active" );
},
mouseenter: function() {
$( this ).addClass( "inside" );
},
mouseleave: function() {
$( this ).removeClass( "inside" );
}
});