首页 > 解决方案 > 我想将不在 dom 上的图像放在 nodeList 中

问题描述

我在 stackOverflow 和其他来源中搜索了很多,但我能找到的只是从 Dom 中提取的 nodeLists。我在 js 文件中创建了自己的元素,并且我想将它们放入一个数组中以便能够操作顺序。

你能帮我看看我哪里错了。

显然这没有奏效。图像已正确创建,但 nodeList 未正确声明。

const img1 = new Image();
img1.src = "../img/afghanistan.png";
img1.alt = "afghanistan";
img1.width = widthCalculation();
img1.height = heightCalculation();

const img2 = new Image();
img2.src = "../img/angola.png";
img2.alt = "angola";
img2.width = widthCalculation();
img2.height = heightCalculation();

const img3 = new Image();
img3.src = "../img/bahamas.png";
img3.alt = "bahamas";
img3.width = widthCalculation();
img3.height = heightCalculation();

const img4 = new Image();
img4.src = "../img/belgium.png";
img4.alt = "belgium";
img4.width = widthCalculation();
img4.height = heightCalculation();

const img5 = new Image();
img5.src = "../img/bolivia.png";
img5.alt = "bolivia";
img5.width = widthCalculation();
img5.height = heightCalculation();

const img6 = new Image();
img6.src = "../img/kiribati.png";
img6.alt = "kiribati";
img6.width = widthCalculation();
img6.height = heightCalculation();

const img7 = new Image();
img7.src = "../img/mongolia.png";
img7.alt = "mongolia"
img7.width = widthCalculation();
img7.height = heightCalculation();

const img8 = new Image();
img8.src = "../img/panama.png";
img8.alt = "panama";
img8.width = widthCalculation();
img8.height = heightCalculation();

let imgCollection = { const img1, const img2 ,img3 ,img4 ,img5 ,img6 ,img7, img8 };

标签: javascriptjquery

解决方案


而不是使用以下内容:

const img1 = new Image();

改用这个:

var img1 = document.createElement("img");

后者将创建一个您可以配置的元素,然后附加到您的集合中。

var images = [];

for (var i = 1; i <= 5; i++) {
  var img = document.createElement("img");
  img.src = `img${i}.png`;
  images.push(img);
}

console.log(images);


推荐阅读