简体   繁体   English

如何将照片动态加载到动态加载的 div 中?

[英]How to dynamically load photos to dynamically loaded divs?

I wrote this code, which creates divs depending on the amount of text files in local directory.我写了这段代码,它根据本地目录中文本文件的数量创建 div。

Then I tried to write additional code, which appends photos to each of these divs.然后我尝试编写额外的代码,将照片附加到这些 div 中的每一个。 Unfortunately, this code doesn't append any photos...不幸的是,这段代码没有附加任何照片......

function liGenerator() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == XMLHttpRequest.DONE) {
        if (xmlhttp.status == 200) {
          var n = (xmlhttp.responseText.match(/txt/g) || []).length;
          for (var i = 1; i < n; i++) {
            $.get("projects/txt/"+i+".txt", function(data) {
              var line = data.split('\n');
              var num = line[0]-"\n";
              var clss = line[1];
              var title = line[2];
              var price = line[3];
              var content = line[4];
              $("#list-portfolio").append("<li class='item "+clss+" show' onclick='productSelection(&#39;"+num+"&#39;)'><img src='projects/src/"+num+"/title.jpg'/><div class='title'><h1>"+title+"</h1><h2>"+price+"</h2></div><article>"+content+"</article></li>");
              $("#full-size-articles").append("<li class='product "+num+"'><div><div class='photo_gallery'><div id='fsa_img "+num+"'><div width='100%' class='firstgalleryitem'></div></div></div><article class='content'><h1 class='header_article'>"+title+"</h1><h2 class='price_article'>"+price+"</h2><section class='section_article'>"+content+"</section></article></div></li>");
          });
        }
      }
    }
  };
  xmlhttp.open("GET", "projects/txt/", true);
  xmlhttp.send();
}   

function pushPhotos() {
  var list = document.getElementById("full-size-articles").getElementsByTagName("li");
  var amount = list.length;
  for(var i=1;i<=amount;i++) {
    var divID = "#fsa_img "+i;
    var where = "projects/src/"+i+"/";
    var fx = ".jpg";
    loadPhotos(where, fx, divID);
  }
}

function loadPhotos(dir, fileextension, div) {
  $.ajax({
    url: dir,
    success: function (data) {
      $(data).find("a:contains(" + fileextension + ")").each(function () {
        var filename = this.href.replace(window.location, "").replace("http://", "");
        $(div).append("<img src='"+dir+filename+"' class='mini_photo'/>");
      });
    }
  });
}

Any ideas on why this code is not working as intended?关于为什么此代码无法按预期工作的任何想法?

The main issue is the space between "#fsa_img" and "i".主要问题是“#fsa_img”和“i”之间的空格。 When I changed it to '"#fsa_img_"+i', the code started work as intended.当我将其更改为 '"#fsa_img_"+i' 时,代码开始按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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