简体   繁体   中英

Javascript call function once loop finishes and jQuery populates content

I'm trying to get my jQuery to work in this flow:

  1. Parse json using $getJson
  2. Loop through returned JSON and create divs for each JSON item
  3. Once done, repeat but instead with another json file and append the results to the existing results.

But as of now I can't call another function AFTER the first loop is done, because the function gets called before the page is populated. How can I finish the populating loop, and then call another function?

I appreciate any help you can give me. Still learning as you can tell.

function test() {
  var i;
  for(i=0;i<=10;i++) {
    $("div#test").append("<div id='"+i+"'></div>");
  }
  when_loop_is_done();
}
function when_loop_is_done() {
  var i;
  for(i=0;i<=10;i++) {
    $("div#test div#"+i).append("<span>foo</span>");
  }
}

Essentially I'm grabbing JSON from a separate page on my server, then looping through and populating the content using variables from that JSON object. The issue is no matter what I do, the second function always gets called before jQuery populates the content. So if I were to call an alert after the loop is done the page would pop up the alert and then load in all of the appended html.

Store your results in a variable or property. Then, use $(document).ready(fn) to wait for the page to finish loading and populate the page or finish your work when it has finished loading.

Your code should look something like this:

   $.getJSON('/remote.json', function (response) {
     // do the first loop using the response json
   })
   .done(function () {
     // do the second json request and loop through the results
   });

Any code you call inside the done() method's callback function will wait until the previous method in the chain is complete. You should definitely review the API documentation for $.getJSON: https://api.jquery.com/jquery.getjson/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM