.on() methodThe .on() method in jQuery is used to attach an event handler to the selected elements.
Use .off() to remove the attached event handler.
.on() method Syntax.on(events[,selector][,data],handler)
| Parameter | Type | Description |
|---|---|---|
events |
String | A string contain space-separated event types and optional namespaces, or just namespaces,such as click,submit,keydown.myPlugin, or .myPlugin. |
handler |
Function | event handler function to execute when the event is triggered. |
selector |
String | A selector used to filter selected elements that trigger the event |
data |
Anything | Data to be passwd to the handler |
.on() method Examplewhen the user clicks any paragraph, shows its text contents as an alert.
$( "p" ).on( "click", function() {
alert( $( this ).text() );
});
.on() method allows a click event on any selector-filtered matched elements--even new ones.
$( "p" ).on( "click", function(index) {
$( this ).after( "<p>new created paragraph"+index+"!</p>" );
});
bind multiple event types
$('#foo').on('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});
bind multiple event handlers simultaneously
$("button").on({
click:function(){$("p").slideToggle();},
mouseover:function(){$("body").css("background-color","red");},
mouseout:function(){$("body").css("background-color","#FFFFFF");}
});
Pass data to the event handler,which is specified here by name.
function myHandler(event) {
alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)
Cancel only the default action
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
});
use return false to prevents the default action from occurring and stops the event from bubbling.
$( "form" ).on( "submit", false );
//or
$("form").on("submit", function() { return false; })
It's equivalent to calling both event.preventDefault() and event.stopPropagation()
$("form").on("submit", function(event) {
event.preventDefault();
event.stopPropagation();
})
