Delegation of events to dynamically generated elements

Asked

Viewed 225 times

3

I will try to be more specific. I have a list <ul>which is populated via jQuery:

var $imovel  = $("#lista-resultados-pesquisa");


$.ajax({
  type: 'GET',
  url: 'imovel.json',
  success: function(data) {
    $.each(data.imovel,function(i, imovel){
        $imovel.append('<li value="'+ imovel.preco +'">Meu conteudo</li>');
    })
  }
});                 

Because the items on my list are not in html, I can’t manipulate them... For example, I need to sort my list according to the attribute value of tags <li>, and I also need to have a button loadMore to limit the amount of elements that appears on the screen. I already have this, the problem is that I cannot manipulate the items in my list "<li>" that are being entered dynamically, so to speak, from my local json file.

I will show you the functions for sorting and loadMore I have with me.

//LOADMORE
            var size_li = $("#lista-resultados-pesquisa .intens-pesquisa").size();
            var x=3;
            $("#lista-resultados-pesquisa .intens-pesquisa:lt("+x+")").show();
            $("#loadMore").click(function () {
                x= (x+3 <= size_li) ? x+3 : size_li;
                $("#lista-resultados-pesquisa .intens-pesquisa:lt("+x+")").show();
                if(x == size_li){
                    $("#loadMore").hide();
                }
            });     

            //ORDENA
                $('.ordena-menor').click(function() {
                  $("#lista-resultados-pesquisa .itens-pesquisa").sort(numOrdDesc).appendTo('#lista-resultados-pesquisa');
                });

                $('.ordena-maior').click(function() {
                  $("#lista-resultados-pesquisa .itens-pesquisa").sort(numOrdCres).appendTo('#lista-resultados-pesquisa');
                });


                function numOrdDesc(a, b) {
                  return ($(b).val()) < ($(a).val()) ? 1 : -1;
                }

                function numOrdCres(a, b) {
                  return ($(b).val()) > ($(a).val()) ? 1 : -1;
                }

Thanks Gurizada, a strong hug and a great weekend to all!

1 answer

2


Delegates the event to the parent element, to an element where the event can be associated with the page load. Instead of delegating to the specific element that does not yet exist. To delegate events to dynamically generated elements, in this case, the li inside #lista-resultados-pesquisa do so:

$("#lista-resultados-pesquisa").on('click', 'li', function(){
   ...
});

I made here a EXAMPLE, as it is works, uncomment the event click below, and take the top to see that delegating the event directly in the element does not work

$('button').on('click', function() {
  for(var i = 1; i <= 10; i++) {
  	$('#lista-resultados-pesquisa').append('<li>clica aqui: ' +i+ '</li>');
  }
});

// tira isto
$('#lista-resultados-pesquisa').on('click', 'li', function(){
alert('Isto resulta');
});

// e coloca isto para veres o que acontece/que não acontece
/*$('#lista-resultados-pesquisa li').click(function(){
alert('isto não resulta');
});*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="lista-resultados-pesquisa">

</ul>
<button>
adicionar elementos gerados dinamicamente
</button>

  • Miguel, you helped me a lot! Thank you very much... In the case of the Loadmore function, I’m not being able to apply. Do you know how to use on() instead of ready()? Big hug!

  • You’re welcome. Which ready? I don’t see

  • I got my dear friend... You were of paramount importance to success! Thank you!

  • You’re welcome @Joãosouza

Browser other questions tagged

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