简体   繁体   中英

Create divs and load each with a file based on ajax call

So I have the below code which is supposed to get a directory of html files, take each one, and load the contents into a new div with the class ".module". My directory and file names are retrieved correctly, a new div is created correctly, but the problem is that only one div is created and it is only loaded with the content from the last file in the directory. Can't seem to figure out why!

   $(document).ready(function() {
        $.ajax({
           url: 'modules/',
           dataType: 'json',
           cache: false,
           success: function(data) 
              {
                 $(data).each
                    (function() 
                       {
                             var filename = this;
                             console.log(filename);
                          $('#wrapper').html('<div class="module editable moveable deletable">');
                          $('#wrapper').append('</div>');
                          $('.module:last-of-type').load("modules/"+ filename);
                       });
              },
              error: function(error){
                 console.log('failed with error ' + error.status);
              }
        });
     });

Replace your .each() with this:

$(data).each(function() {
  var filename = this;
  console.log(filename);
  $('#wrapper').append($("<div>").addClass("module editable moveable deletable"));
  $('.module:last-of-type').load("modules/" + filename);
});

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