javascript - External jQuery file loop skips over first or last item -


i'm loading information page external javascript file. file finds divs on page class name, populates div's content based on custom attribute, link api. function in external file loops through each div class , dynamically populates div's id.

here code divs on page:

<div class="classname" data-apisrc="www.someapi1.com" id="box1"></div> <div class="classname" data-apisrc="www.someapi2.com" id="box2"></div> <div class="classname" data-apisrc="www.someapi3.com" id="box3"></div> 

here code in external file:

$(function() {     $("div.classname").load("https://...somewebsite.com.html div.box-container");      var i=0;      var box = $("div.classname");      $(box).each(function(apisrc, div_id) {         i++;          var apisrc = $(this).attr("data-apisrc");         var div_id = 'box'+i;         $(this).attr('id',div_id);         $(this).val(i);          $this = $(this);          $.ajax({             type: "get",             url: apisrc,             async: true,             success: function(result) {                 ...loads content each div             },             error: function() {                 $this.text("content not loaded");                 //alert('error');             }         });     }); }); 

this function in external file. being called in current file @ top of page, shouldnt matter because function wrapped in document.ready function

there 3 of these divs on page. reason, shows content second , third div , skips first until reload page several times.

i don't see wrong function. advice?

because $("div.classname").load("https://...somewebsite.com.html div.box-container"); overriding content in first (or arbitrary) div

and times (few of many tried) load resolves first, , ajax changes inside ajax success affecting in dom. if need both contents (from load(...)) , adding inside ajax success on top of that, once load completed, pass callback second argument of load, , move entire code there.

eg:

$("div.classname").load("https://...somewebsite.com.html div.box-container", function(){     //place code want execute after load completed }); 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -