What is the difference between $ (document) .on () and $ (element) .on ()

I know about the uses and goals of jquery.on () because I use this.

But I want to know what is the difference between $(document).on() and $(element).on() in this scenario:

 <html> ... <body> ... <table id="table-user"> <thead>...</thead> <tbody> AJAX DYNAMIC CONTENT </tbody> </table> .... <script> $(document).on('click','.btn-edit',function(){ go_edit(); }); $('#table-user').on('click','.btn-edit',function(){ go_edit(); }); </script> </body> </html> 

Is any performance different or something else in between?

+8
source share
2 answers

The main difference is already answered by @Mukesh. I will try to add one more thing.

When you click (or any other event) on an element (e.g. div or ) in the html document, this click event extends to the parent elements of this element. So, if you have a structure like this:

 <div> <table> <tr> <td> <button>Click Me</button> </td> </tr> </table> </dvi> 

and you click on the button, this click will apply to td, then to tr, then to the table, and then, finally, to the document itself.

Now let's say that you registered a click event on the document ( $ document.on ('click', ...) ), as well as on the button ( $ (button. On ('click', ...)) ), both of which perform several different actions. Then, if you click on the button, the corresponding button action will be performed, and the corresponding $ (document) action will be performed.

To prevent a button from being clicked for distribution on the document itself, you need to take action on the button click handler (for example, stopPropagation, etc.).

+10
source
 $(document).on('click','.btn-edit',function() 

This links the click event to the document and all the children inside it. This method is called delegated event handling.

 $('#table-user').on('click','.btn-edit',function() 

directly binds the click event to user # table-user. captures an event directly on an element.

+9
source

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


All Articles