jQuery does not see content loaded via ajax

Asked

Viewed 3,942 times

0

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

For example: on a parent page I have a script loaded with the page. On this parent page, I have a DIV with ID="filho". When, a button on the parent page is clicked, I press the result in 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’s like it doesn’t exist. How to solve this?

  • 2

    Can you put your code here? I think the problem is delegation. You should use $(pai).on('click' ,'filho', function(){ ...

  • I understood the link you posted before. But, what about when the event is not triggered via click? Example: $(Document). ready(Function(){ load a page via load or ajax ...});

  • 1

    The best is to put a concrete example of code. Without seeing can be a lot...

  • Your explanation is very confusing, try to put part of the code to better view the problem and explain in topics.

4 answers

5


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 must use a delegate event.

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

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

4

You need to use the live method case jQuery < 1.7 and the method on if jQuery > 1.7.

When the DOM is loaded if the element does not exist, even if there is an event for it, it will not be "Linked" to that event when it comes into existence unless you use the method on. It is good practice to always use the on instead of click.

Then change

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

for

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

0

I 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);
});

0

I was having the same problem and what worked was using the .live():

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

})

Documentation

Browser other questions tagged

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