javascript - 我想将不在 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 };
解决方案
而不是使用以下内容:
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);
推荐阅读
- python - 返回和检查方法执行的 Pythonic 方式
- latex - 如何实现括号乳胶引用格式?
- asp.net-core - 如何列出 ASP.NET Core Web 服务的端点?
- python-3.x - 在 Python 中将 str 对象转换为关键字
- python - 键绑定命令在调用时给出不同的输出
- delphi - 两个 TTime 变量之间的差异
- android - 顺便说一句,url_launcher 与 android_intent_plus 的区别
- css - 带有 css 或 js 文件的 AWS Lambda 静态网站,没有在 s3 存储桶中托管静态文件
- asp.net-core - ASP.NET Core 5 DbSet 表
- tailwind-css - 顺风应用指令不起作用顺风