Which one is better to use for .click in the bottom list

Please vote for me, which one in the lower list is better?

I have HTML:

<div id="container"> <button class="btn">Click Here 1</button> <button class="btn">Click Here 2</button> <button class="btn">Click Here 3</button> <button class="btn">Click Here 4</button> <button class="btn">Click Here 5</button> <button class="btn">Click Here 6</button> <!-- A lot of buttons --> <button class="btn">Click Here n - 2</button> <button class="btn">Click Here n - 1</button> <button class="btn">Click Here n</button> </div> 

And Javascript with jQuery:

Case 1.1:

 $(".btn").click(function(e){ //@todo something here }); 

Case 1.2:

 var doSomething = function(e) { //@todo something here } $(".btn").click(doSomething); 

Case 2:

 $("#container").click(function(e){ if( $(e.target).is(".btn") ) { //@todo something here } }); 

I confuse the litle bit, what is different between them?

+4
source share
4 answers

You should use the new jQuery on () function

 $(document).on("click", ".btn", doSomething); 

so that

  • dynamically added content will be added.
  • jQuery does not have to spend time searching and wrapping all the affected buttons with a handler; all clicks will propagate to the context, and jQuery will apply them if they match the .btn selector in this case

If you know that all of your buttons will be in #container, then you will use this as a context, not a document.

 $("#container").on("click", ".btn", doSomething); 
+5
source

Cases 1.1 and 1.2 are essentially the same. The only thing you get from 1.2 is that you can call the function yourself. If necessary, then 1.2 should be used, if not, or this is normal.

Case 2 is actually not functionally equivalent to the others. This is essentially equivalent to live . Using click will only bind to the corresponding elements at the time the click called. Case 2 (and live ) will match the selector during the event. If, after calling this code, .btn elements were added. Case 2 will also allow you to click on them.

EDIT: Note that in 1.7 live is replaced with on with certain parameters.

+2
source

Case 2 would be best if you plan to use doSomething elsewhere. If not, then 1 and 2 are equally good. Of course, only talking style is wise ... the functionality is the same.

0
source

Case 1.1 is a common anonymous function for your event handler and is the most commonly used case.

Case 1.2, which you would use if you also want to call the function directly, and not just as an event handler, so you need to refer to it somehow.

Case 2 is useful if you have so many things, because it creates only one event handler instead of many. This case will also catch new elements of the btn class that are dynamically added to #container

0
source

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


All Articles