The difference between $ (document) .on and $ ('# submit').

Please let me know the difference between the following.

I am new to such activities.

$('#myButton').on('click', function () { // Some code }); 

and

 $(document).on('keyup', '#myButton', function () { // Some Code }); 

and

 $('#myButton').click(function () { //Some code }); 
+4
source share
1 answer

From the documentation


Delegated events have the advantage that they can handle events from descendant elements that will be added to the document later. By choosing the item that is guaranteed to be present when the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element can be a view container element in the Model-View-Controller design, for example, or a document if the event handler wants to control all the bubble events in the document. The document element is available at the beginning of the document before loading any other HTML code, so it is safe to attach events there without waiting for the document to be ready.

In a data table with 1000 rows in the body, this example attaches a handler to 1000 elements:

 $( "#dataTable tbody tr" ).on( "click", function() { alert( $( this ).text() ); }); 

The approach with delegated events attaches the event handler to only one element, that is, and the event only needs a bubble at one level (from clicking tr to tbody):

 $( "#dataTable tbody" ).on( "click", "tr", function() { alert( $( this ).text() ); }); 

Note. Delegated events do not work for SVG.


See also:

+4
source

Source: https://habr.com/ru/post/1263235/


All Articles