Set click for elements not yet existing

Asked

Viewed 76 times

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?

  • 1

    you must set to class="item" in the read that this adding

  • @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

  • @Sergio, I don’t really know if it was a duplicate...

  • @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.

1 answer

4


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

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

in the above example, it will apply the event click for all elements with the class .item pertaining to ul, idenpedent of the .item already exist 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>

  • Yes yes! That’s right, it worked perfectly. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.