如何循环 table 中的图像,获取所有图像的 src 并应用于新 table 中的新图像?

How do I loop over images in table, get the src of ALL images and apply to new images in new table?

我正在循环浏览 table 中的图像,尝试获取来源,然后将该 src 应用到另一个 table 中的新图像。我已经设法在新的 table 单元格(已测试)中创建新的图像对象,但出于某种原因,我只能得到最后一张要显示的图像。好吧,实际上我知道这是因为循环每次都会覆盖变量并且它在应用时具有最后一个值,但我不知道如何获取它们。这是相关代码。如果您需要更多,请大声疾呼或查看 Why can't I get my images to appear in table cells/nodes.. maybe I can get some closure? 感谢您的帮助。

newImages = newTable.getElementsByTagName('img');

for(var i = 0; i < newImages.length; i += 1) {
    var picSource = newImages[i]['src'];
    console.log(picSource);//This logs the path to the four different images
    var newImg = new Image();//creates a new image for each
    newImg.src = picSource;//gives each image src?? Just gives the last image
}

有两种方法可以解决这个问题,要么创建新的 img 元素,要么复制 src 属性 ,或者只是克隆元素。例如,如果您有以下 table:

<table id="t0">
 <tr><td><img src="a.png">
 <tr><td><img src="b.png">
 <tr><td><img src="c.png">
</table>

您可以使用 document.images 获取文档中的所有图像,但您只需要 table 中的图像,因此您可以:

var images = document.getElementById('t0').getElementsByTagName('img')

这是一个实时集合(如果您从 table 添加或删除图像,它将自动更新),或者使用选择器:

var images = document.querySelectorAll('#t0 img')

这是一个静态集合,无论您对 table 做什么,它都保持不变。所有使用的浏览器都支持第一种方法,但大多数浏览器也会支持选择器版本。

要通过复制 src 属性 制作另一个具有相同图像的 table,您可以这样做:

var table = document.createElement('table');
var row, cell, img;

for (var i=0, iLen=images.length; i<iLen; i++) {  
  row = table.insertRow(-1);
  cell = row.insertCell(-1);

  // create new image and append to cell
  img = new Image();
  img.src = images[i].src;
  cell.appendChild(img);
}

使用clone方法,最后3行可以替换为:

  cell.appendChild(images[i].cloneNode(false));

最后,将新的table添加到文档中:

document.body.appendChild(table);