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 element #botao is pressed will be added the element #tela2 inside #tela.
In the second part it defines that when the element #tela2 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 function on, that can inform as second parameter a child selector to receive the event - even if it does not yet exist on the page. In fact, the event is assigned to the parent element, which will always check who was the target element of the click (this is 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>
<div id="tela">
<div id="botao">BOTAO</div>
</div>
See that with on, the event will be associated with the parent element, #tela, but we inform that we just want the function callback is executed if the target element of the click is the element #tela2.
Note: also makes no sense you add multiple elements on the page with same id. Why it is considered wrong/bad to repeat an HTML ID? Be careful with that too.
I tried to do ,this but I could not Anserson. On this blue screen will have other clickable elements
– thiago
If his simplifying is true to the problem, so should solve. Your problem is that the
clickdoes not work for elements that are added dynamically. You can do this with theonand pass three parameters to it: event, child element selector and function callback, as presented in the above-mentioned question.– Woss
i edited the post. I added a button. That calls the screen 2.It’s closer to my problem... And on this screen 2 will have other clickable elements
– thiago
You understand why your code doesn’t work?
– Woss
No ... so far I could not solve the problem.
– thiago
but I appreciate the help
– thiago