What are the advantages of assigning events through the universal on() method before assigning events, for example, using the click() , hover() , keydown() ?
2 answers
This method does not give any advantages, simply because all the listed methods internally use this method :
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); However, it can be noted that the creation does not use all the parameters of the on method. Read more about this method in the help .
The selector parameter is not used, allowing you to specify from which of the nested elements to catch the event. If null or omitted, events will be caught, only on elements from the set.
For comparison:
Same behavior
$(selector).click(function(){...}); $(selector).on('click',null,function(){...}); Still the same behavior
$('parent child').click(function(){...}); $('parent child').on('click',null,function(){...}); The behavior will be different, since the handler itself is hung on the parent, so it does not matter at what point the child element was added by which it was clicked.
$('parent').on('click','child',function(){...}); - they write that click (), hover () .. is not hung on dynamically created elements, and on () is hung - Dimon
- @Dimon, not really. Read the last two paragraphs in the answer. - Grundy
- @Dimon, added examples, in which case the behavior will be different. - Grundy
- Thanks for the reply - Dimon
- one@PavelMayorov, there is only one thing except :-) so don’t need to be here :-) - Grundy
For example, there is a structure
<div id="container"> <div class="elem"></div> <div class="elem"></div> <div class="elem"></div> <div class="elem"></div> <div class="elem"></div> </div> the task is to catch clicks on elements
you can just
$('.elem').click(f) but then a lot of handlers are created
instead it’s better to do it like this
$('#container').on('click', '.elem', f) in this case, the handler creates only one additional item added AFTER the handler is connected, elements such as live