javascript - 将 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");
}
解决方案
当您通过行迭代器访问它时,您的图像 url 首先使用每个单元格的行进行索引,由于您的条件,该迭代器仅返回前 4 个图像:for (var i = 0; i < 4; i++)
。因此,您还需要使用第二个迭代器来获取相应的图像:
cell.appendChild(images[(j*4) + i]);
推荐阅读
- cmake - 如何在 CMake 中对静态库之间的传递依赖关系进行建模?
- python - Python多维数组
- php - 获取字母数字数组php中的最大元素
- python - 为什么我无法访问 django 模板中的外键信息。
- python - 为什么 MNIST 数据集的输入范围应该在 0 和 1 之间?
- python - python中的gzip库是否尝试在内存中打开整个文件?
- android - 光标显示sql记录按DESC排序
- angularjs - 使用 AngularJS 更新 HTML 标头变量
- javascript - Angular 中的 TypeScript/JavaScript
- reactjs - TypeScript 不检查 React.Component 的 propTypes,我该如何解决?