Pergunta

I have an html page called search.html that contains the following jQuery code :

$(document).ready(function(){
...some code // THIS IS THE CODE I'M INTERESTED IN
}
...some other code

And I have another html page that contains the following jQuery code:

$("#display_area").load("search.html") // #display_area is a div

The problem is, when this jQuery code is called, it inserts the content of search.html but executes the code that I'm interested in (the code in the $(document).ready() section) immediately, it doesn't wait for the DOM to be ready, which obviously generates errors.

The other codes (outside the $(document).ready() section) execute normally without any problems.

Placing the code within the callback function of the .load() function doesn't work either, the code fires while the DOM isn't ready.

Is there any way to solve this ? Any help would be appreciated.

EDIT : I just want to specify, that the search.html contains a DOM of its own that is going to be inserted in the #display_area div, and I want my code to fire when the #display_area div has finished loading all its new DOM (content) that was loaded through the load() function.

Foi útil?

Solução

I think your mistake is that $(document).ready is called when your main page's DOM is ready the first time. Changing the DOM doesn't re-fire $(document).ready. Your confusion comes from the fact that you call $("#display_area").load("search.html") when the page loads. At that time, the original DOM is not finished yet, when it is, $(document).ready is fired, later (at some random moment) your Ajax function returns. And that's it.

To execute code after your Ajax .load function returns, use this

$("#display_area").load("search.html", function() { 
    alert('New DOM elements should be available now'); 
    // do more stuff 
} );

Edit: OK, so here's the whole scheme:

  • In your main html page, call $("#display_area").load("search.html") only when the DOM is ready. So do this call from a $(document).ready function in your main page
  • Next, use the callback function of .load as I described, do whatever you want in there
  • Finally, if you want code in search.html to be executed after it is loaded: agree upon a function name between your main page and search.html. This function is defined in search.html and called from the .load callback.

Outras dicas

$(document).ready() in search.html will fire off when search.html is loaded, which will occur when .load() is done, even if the other page is not done loading.

You could try placing the JS code on search.html in a normal function and then in the callback function of .load() you call this 'newly added' function. Populating the div can still occur in the .load() callback function.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top