Element.AppendChild()给出意外结果:删除现有的孩子



我正在网站上创建'照片'页面。它使用PHP在目录中检索文件名,然后尝试使用JavaScript编程创建DIV(其中图像(。但是,当我尝试创建" W3-Third"divs时,编辑InnerHTML,以使其嵌入图像,并且(问题的步骤(将它们添加到" W3-Row" Div中,它将删除现有的孩子。因此,每排只有一个图像。

我一直在寻找替代代码/解决方案,但是element.appendchild((函数似乎是唯一的方法。我尝试了element.Children.push((,但是element.Children是[htmlcollection],我猜是只读。

$.getJSON("content/photospage/get_filenames.php", function(data){
    var photoFileNames = data;
    console.log(photoFileNames.length + " images to display.");
    var photosDiv = document.getElementById("divPhotos");
    for(var i = 0; i < photoFileNames.length; i += 3){
      console.log("Loop! i=" + i);
      var newRow = document.createElement("div");
      newRow.classList.add("w3-row");
      newRow.classList.add("w3-padding-8")
      var newImg1 = newImg2 = newImg3 = document.createElement("div");
      newImg1.classList.add("w3-third")
      newImg2.classList.add("w3-third")
      newImg3.classList.add("w3-third")
      newImg1.innerHTML = "<img src='" + dir + photoFileNames[i] + "' class='w3-round w3-margin-bottom constrained'>";
      newRow.appendChild(newImg1);
      console.log("displayed img " + (i))
      if(i+1 < photoFileNames.length){
        newImg2.innerHTML = "<img src='" + dir + photoFileNames[i+1] + "' class='w3-round w3-margin-bottom constrained'>";
        newRow.appendChild(newImg2);
        console.log("displayed img " + (i+1))
      }
      if(i+2 < photoFileNames.length){
        newImg3.innerHTML = "<img src='" + dir + photoFileNames[i+2] + "' class='w3-round w3-margin-bottom constrained'>";
        newRow.appendChild(newImg3);
        console.log("displayed img " + (i+2))
      }
      console.log(newRow.children);
      photosDiv.appendChild(newRow);
    }

默认存在的HTML元素:

<div class="w3-container w3-content w3-center w3-padding-32 " id="divPhotos">
</div>

很抱歉上述大量代码。感谢您的帮助,我很高兴澄清我未提及的任何内容。:(

另外,我知道代码笨拙且效率低下,所以让我知道您是否可以拿起我可以做得更好的任何事情。再次感谢!:(

var newImg1 = newImg2 = newImg3 = document.createElement("div");

您已经在内存中创建了一个一个对象( HTMLDivElement(,其中3个变量名(newImg1newImg2newImg3(参考。您没有3个单独的元素。当您使用其中一个元素调用appendChild时,您可以将其从以前存在于DOM中的任何地方删除。

由于您需要单独的元素,因此应该明确地进行:

var newImg1 = document.createElement("div");
var newImg2 = document.createElement("div");
var newImg3 = document.createElement("div");

您可以通过使用另一个for循环而不是创建单独的独立元素来使代码不重复:

for (let j = 0; j < 3; j++) {
  const thisIndex = i + j;
  if (thisIndex >= photoFileNames.length) {
    break;
  }
  const img = document.createElement("div");
  img.innerHTML =  "<img src='" + dir + photoFileNames[thisIndex] + "' class='w3-round w3-margin-bottom constrained'>";
  newRow.appendChild(img);
}

最新更新