2
$(".item").on('click',function(){
alert($(this).text());
});
count=0;
$("#new").on('click',function(){
count++;
$li = $("<li class='item'>LI "+count+"</li>");
$("ul").find('.item').last().after($li);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
<li class='item'>LI 0</li>
<li id='new'>+ Adicionar li</li>
</ul>
I made a simple code above to demonstrate the problem in question.
As you can see, after a new element <li>
be added it does not inherit the click event that was set before in the code
How could I make him inherit this event without having to set it up again every time <li>
is added?
you must set to
class="item"
in the read that this adding– Guilherme Lautert
@Guilhermelautert you were right, really forgot to add. but as tested before had no effect at all. I changed now and continued the same problem
– Silvio Andorinha
@Sergio, I don’t really know if it was a duplicate...
– Silvio Andorinha
@Silvioandorinha this question has very complete answers about the delegation problem. If it is not this can be this or this or others with the same problem.
– Sergio