What you can is assign to document
an event click
in its class, since the elements are being generated after the DOM
has already been loaded, so it will not take the event of the click
, do as follows:
$(document).on('click', '.option', function(){
//Evento do click
})
That way you say whenever you’re clicked on document
in that classe
he performs this method!
Another way is to use jQuery delegate(), so you say that in every element(div) in the class (option1) it will perform this method
$('div').delegate('.option1','click', function() {
//Evento do click
});
I added 3 examples separated by a line, check that in the first example every click it generates an element, but the generated element has no action, already in the second and third examples the generated elements have the desired action:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="conteudo1">
<div class="option1" data-option="1">Click1</div>
</div>
<hr>
<div class="conteudo2">
<div class="option2" data-option="1">Click1</div>
</div>
<hr>
<div class="conteudo3">
<div class="option3" data-option="1">Click1</div>
</div>
<script>
$('.option1').on('click', function () {
var option = $(this).data('option');
$('.conteudo1').append("<div class='option1' data-option='"+(option+1)+"'>Click"+(option+1)+"</div>");
});
$(document).on('click','.option2', function () {
var option = $(this).data('option');
$('.conteudo2').append("<div class='option2' data-option='"+(option+1)+"'>Click"+(option+1)+"</div>");
});
$('div').delegate('.option3', 'click', function(){
var option = $(this).data('option');
$('.conteudo3').append("<div class='option3' data-option='"+(option+1)+"'>Click"+(option+1)+"</div>");
})
</script>
just do it like this
$(document).on('click', '.option', function(){})
– Rafael Augusto
A simple question, if this element contains a link and you are using redirect based on this link when clicked, Poruqe does not make your life easier and uses a
<a href='index.php?pg=13&id=1'><small><b>[Texto]</b></small> Nome</a>
?– Erlon Charles
Because all the
<li>
are defined as suchul > li{
and if you put a<a>
before the<li>
classes will not be applied. I know I could change but would like to know other alternatives.– I_like_trains
In fact, there are no problems in your code, the problem is only where it is running and when it is running, because at the moment, you are running this click event assignment before the element even exists on the page, so there is no way to work, then you just need to put this your code inside the method
.done()
from your ajax, after the element has been played on the page, so it will run only when the element already actually exists.– Paulo Roberto Rosa