Setar click for elements not yet existing [duplicate]

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 <li> element is added it does not inherit the click event that was set earlier in the

How could you make it inherit this event without having to go back every time a <li> is added?

    
asked by anonymous 15.03.2016 / 14:29

1 answer

4

In this case you can use the on event on the ul and pass the li as the second parameter.

$("ul").on('click', '.item', function(){
  alert($(this).text());
});

In the above example, it will apply the click event to all elements with the .item class% to ul , whether .item already exists or not.

$("ul").on('click', '.item', function(event){
  alert(this.textContent);
});

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>
    
15.03.2016 / 14:35