首页 > 解决方案 > 将 IMG 附加到表

问题描述

我无法将整个预加载的图像数组附加到创建的表中。此代码填充最后一列。但我想用每个单元格的每个图像填充每个单元格。

我哪里错了?我在这里想念什么?

function generate_table() {

  //preload Image Array
  var preload = ["../../images/Large/bcpot002_r1_c1.jpg", "../../images/Large/bcpot002_r2_c1.jpg", "../../images/Large/bcpot002_r3_c1.jpg","../../images/Large/bcpot002_r4_c1.jpg",
            "../../images/Large/bcpot002_r1_c2.jpg", "../../images/Large/bcpot002_r2_c2.jpg", "../../images/Large/bcpot002_r3_c2.jpg","../../images/Large/bcpot002_r4_c2.jpg",
            "../../images/Large/bcpot002_r1_c3.jpg", "../../images/Large/bcpot002_r2_c3.jpg", "../../images/Large/bcpot002_r3_c3.jpg","../../images/Large/bcpot002_r4_c3.jpg",
            "../../images/Large/bcpot002_r1_c4.jpg", "../../images/Large/bcpot002_r2_c4.jpg", "../../images/Large/bcpot002_r3_c4.jpg","../../images/Large/bcpot002_r4_c4.jpg",
            "../../images/Large/bcpot002_r1_c5.jpg", "../../images/Large/bcpot002_r2_c5.jpg", "../../images/Large/bcpot002_r3_c5.jpg","../../images/Large/bcpot002_r4_c5.jpg",];


  //preload Images
  var images = [];
  for (i = 0; i < preload.length; i++) {
      images[i] = new Image();
      images[i].src = preload[i];
      images[i].className="myImg";
  }

  // get the reference for display div
  var imagediv = document.getElementById("test");

  // creates a <table> element and a <tbody> element
  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  // creating all cells
  for (var i = 0; i < 4; i++) {
    // creates a table row
    var row = document.createElement("tr");
    row.setAttribute("class", "myTr");
for (var j = 0; j < 5; j++) {
  // Create a <td> element and a text node, make the text
  // node the contents of the <td>, and put the <td> at
  // the end of the table row
  var cell = document.createElement("td");
  cell.appendChild(images[i]);
  cell.setAttribute("class", "myTd");
  row.appendChild(cell);
}

// add the row to the end of the table body
tblBody.appendChild(row);
  }

  // put the <tbody> in the <table>
  tbl.appendChild(tblBody);
  // appends <table> into <body>
  imagediv.appendChild(tbl);
  // sets the border attribute of tbl to 2;
    tbl.setAttribute("cellpadding", "0");
    tbl.setAttribute("cellspacing", "0");
    tbl.setAttribute("class", "myTable");


}

标签: javascriptimagedom

解决方案


当您通过行迭代器访问它时,您的图像 url 首先使用每个单元格的行进行索引,由于您的条件,该迭代器仅返回前 4 个图像:for (var i = 0; i < 4; i++)。因此,您还需要使用第二个迭代器来获取相应的图像:

   cell.appendChild(images[(j*4) + i]);

https://jsfiddle.net/mjnxhwkL/


推荐阅读