When the page loads, your JS code will be executed:
$("#botao").click(function () {
$("#tela").append('<div id="tela2"></div>');
});
$("#tela2").click(function () {
alert("quero que apareça");
});
In the first part it defines that when the #botao
element is pressed the element #tela2
within #tela
will be added.
In the second part it defines that when the #tela2
element is pressed an alert message appears on the screen; but at this time there is no element #tela2
on the page - it will only exist after #botao
is pressed. That is, the event will be added to no element and will never occur during page execution.
To solve this, you need to use the on
function, which can enter a child selector as the second parameter to receive the event - even if it does not already exist on the page. In fact, the event is assigned to the parent element, which will always check who was the target click element (that's the big difference between the functions).
What is the difference between .on ("click", function () {}) and .click (function () {})?
$("#botao").click(function() {
$("#tela").append('<div id="tela2"></div>');
});
$("#tela").on('click', '#tela2', function() {
alert("quero que apareça");
});
#tela {
width: 600px;
height: 450px;
background: red;
}
#tela2 {
width: 300px;
height: 250px;
background: blue;
}
#botao {
width: 50px;
height: 45px;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="tela">
<div id="botao">BOTAO</div>
</div>
Notice that with on
, the event will be associated with the parent element, #tela
, but we only want the callback function to be executed if the target element of the click is element #tela2
.
Note: It also does not make sense for you to add multiple elements to the page with the same id
. Why is it considered wrong / bad to repeat an HTML ID? Be careful about this as well.