1
I will show examples only of the click event to be simpler to explain, but this is related to any jquery event.
When I started using jquery I only used the click event as follows:
$("button").click(function(){
alert('ok');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Confirmar</button>
Which, by the way, worked really well, but then I started doing it this way:
$("#area").html($("<button/>").text('Outro botão'));
//Primeira forma
$("button").click(function(){
alert('ok 1');
});
//Segunda forma
$("button").on('click', function(){
alert('ok 2');
});
//Terceira forma
$('#area').on('click', 'button', function (event) {
event.preventDefault();
alert('ok 3');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Confirmar</button>
<div id="area"></div>
I put two more examples, the "second way" I started using because I noticed that sometimes when I created an element dynamically with jquery the "first way" of using the click event did not work, I used this form for a long time, until one day it also did not work then figure out the "third way" and so I can put the event click on any element without problems.
But my "technique" is the following, I try the first, it does not work I go to second and in turn did not work step to third.
What I want to know is why, this is a feature of jquery, it’s because of javascript, because sometimes it works and because sometimes it doesn’t work, that’s what I wanted to know, I use events but I don’t know why this behavior.