jQuery: What's the proper way to use (document).ready(); in a .click() and .load() combination?

StackOverflow https://stackoverflow.com/questions/19528244

  •  01-07-2022
  •  | 
  •  

Pregunta

I'm trying to create a menu for a mobile app which trades the contents of my #content - DIV to new content from a .HTML - file.

I'm using this code:

$(document).ready(function(){
    $('#menu li').click(function(){
        $('#content').load(this.id + '.html #content *');               
    });
});

This works, except for one HTML-File:

<div id="content">  
    <div id="map"></div> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script src="assets/default.js" type="text/javascript"></script> 
    <script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js" type="text/javascript"></script>              
    <script src="assets/map.js" type="text/javascript"></script> 
</div> 

I'm trying to load a map which is generated by the Leaflet-API, but there's only the empty DIV-Container (#map) parsed by every browser.

I think the problem might be that my map.js isn't fired after the DOM is built. Tried to fix this with $(document).ready() but unfortunately it doesn't work.

Any suggestions?

Would be great, cheers!

¿Fue útil?

Solución

From the load jquery docs you can read

Script Execution

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

And you are calling load with a selector expression...

I would do in other way.

  1. Modify your map.js to contain a function (i.e mapInit ) that executes your map stuff.
  2. Put all this scrips tag in head of the general html document.
  3. Call load with a callback to your map function

    $(document).ready(function(){
      $('#menu li').click(function(){
        $('#content').load(this.id + '.html #content *',mapInit());               
      });
    });
    
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top