jQuery does not see content loaded via ajax

0

How can I make the elements loaded in the layout to be viewed by jQuery?

For example: on a parent page I have a script loaded along with the page. On this parent page, I have a DIV with ID="filho" . When a button on the parent page is clicked, I load the result into this "child" DIV. However, if I want to access some element that has just been loaded through jQuery that is already loaded on the page, it does not work. It is as if it did not exist. How do I resolve this?

    
asked by anonymous 18.03.2014 / 22:52

4 answers

4

You need to use a function that will be called as soon as the page is loaded (callback)

For example:

$('div').load('http://pagina',function(){ /* Codigo da função quando o conteúdo existir */ })

If the HTML being loaded is dynamic and has events, you should use a delegate event.

For example: (note that in this example construction element # div1 must exist before loading the content and the #btAction button is part of the HTML that will be loaded)

$('#div1').on('click','#btAcao',function(){ 
    /* codigo do clique aqui */
})
    
18.03.2014 / 22:59
4

You need to use the LIVE method for jQuery < 1.7 and the method ON jQuery case > 1.7.

When the DOM loads if the element does not exist, even if there is an event for it, it will not be "bound" to this event when it exists unless you use the on method. It's a good practice to always use on instead of click .

Then switch

$('selector').click(function(){
   //ação para o click
});

by

$('selector').on('click',function(){
   //ação para o click
});
    
18.03.2014 / 23:23
0

I had the same problem and what worked was to use .live() :

$('#div1').live('click','#btAcao',function(){ 

})

Documentation

    
02.03.2015 / 21:53
0

I have decided as follows

$("#meudiv").on("click", ".minhaclasse", function(){
   // Aqui pego o valor do objeto clicado, no caso minha classe
   var valor = $(this).val();
   alert(valor);
});
    
12.09.2018 / 19:23