Home >Web Front-end >JS Tutorial >Detailed explanation of on() method usage examples in jQuery_jquery
This article analyzes the usage of jQuery on() method with examples. Share it with everyone for your reference. The specific analysis is as follows:
1. Use of jQuery on() method:
on(events,[selector],[data],fn)
events: One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
selector: A selector string for the filter's descendants of the selector element that triggered the event. If the selector is null or omitted, the event is always fired when it reaches the selected element.
data: When an event is triggered, event.data must be passed to the event handler function.
fn: The function executed when the event is triggered. The false value can also be used as a shorthand for a function that returns false.
2. Advantages of jQuery on() method:
1. Provides a method for unified binding of events
2. It still provides the advantages of .delegate(). Of course, you can also use .bind() directly if necessary
3. Comparison with .bind(), .live(), .delegate():
1. In fact, .bind(), .live(), .delegate() are all implemented through .on()
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
Die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function(selector, types, fn) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
2. The cost of using .bind() is very high. It will hook the same event handler to all matching DOM elements
3. Don’t use .live() anymore, it is no longer recommended and has many problems
4. .delegate() will provide a good way to improve efficiency, and we can add an event handling method to dynamically added elements.
5. We can use .on() to replace the above three methods
4. Examples of using jQuery on() method
1. Bind the click event and use the off() method to remove the method bound to on()
2. Multiple events are bound to the same function
3. Bind multiple events to different functions
4. Bind custom events
5. Pass data to function
$(document).ready(function(){
$("p").on("click", {msg: "You just clicked me!"}, handlerName)
});
6. Applicable to uncreated elements
This is a new paragraph.
").insertAfter("button");I hope this article will be helpful to everyone’s jQuery programming.