What is the difference of $ ('.boot'). on ('click') for $ (document) .on ('click', '.botao')? [duplicate]

0

I searched and could not find anything (probably because I do not know how to search). Anyway, does anyone know?

NOTE: I do not want to know the difference between .click and .on ('click'), please read both options carefully. What I want to know is the difference in reference to the element that will receive the action before saying what action or after (putting the document in the place that used to be the element).

$('.botao').on('click') and $(document).on('click', '.botao')

    
asked by anonymous 11.10.2018 / 20:16

2 answers

5

When you use the:

$('.botao').on('click');

You are linking the click event to each element that contains the existing ".botao" class in the document. The main problem with this method is that if you need to add an element dynamically with the same ".botao" class, it will not have the click event as it was added to the document later. >

What about:

$(document).on('click', '.botao');

In this case, the click event is linked to the document itself, not to the specific elements of the ".botao" class. This is the most recommended method to use since when adding new elements to the document they will still have the click event reference linked to the document.

    
11.10.2018 / 21:58
2

See this example: buttons 1 and 2 will have 2 alerts and button 3 will only have one after it was inserted later in the DOM.

link

    
11.10.2018 / 22:09