将IMG附加到表

时间:2018-10-23 05:07:19

标签: javascript image dom

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

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

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");


}

1 个答案:

答案 0 :(得分:0)

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

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

https://jsfiddle.net/mjnxhwkL/