문제

consider a simplified version of what I'm running:

<html>
   <head>
      <script src="data.js"></script>
      <script src="content.js"></script>
   </head>
   <body>
      <div id="contentGoesHere"></div>
   </body>
</html>

There is obviously much more to this, but this is the basic jist. Within content.js, I have several functions that load markup into my div based on json data included in the data.js. In addition to these functions is the following line:

$(document).ready(function()
{
    loadContent();
});

for all intents and purposes, load content is loading just fine, but within that code is a call to perform a jquery .show() of the first div among several divs that get loaded in after they all get appended to the container element. That code doesn't executing, almost as if the divs don't yet exist. So I tried late loading:

<html>
   <head>
      <script src="data.js"></script>
   </head>
   <body>
      <div id="contentGoesHere"></div>
   </body>
   <script src="content.js"></script>
</html>

sure enough, both result in the first panel being displayed. Why would late loading the file that has the $(document).ready() function in it make a difference if .ready() is supposed to wait until the DOM is loaded anyway?

도움이 되었습니까?

해결책

You are appending extra DOM elements with Javascript after the DOM is ready. $(document).ready() fires after the initial DOM is loaded. That means what is sent in the initial request. It doesn't know about your dynamic appends in an external Javascript.

Furthermore, scripts included in the <head> section get loaded synchronously before the <body> section gets loaded.

다른 팁

Try to wait for the entire document is ready, more or less like this:

$(window).load(function() {
  //code
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top