javascript - 将图像元素数组分配给 DOM id
问题描述
我有一组表示 .png 元素的 URI,例如“./img/diamond-red-solid-1.png”。
我想将数组“gameDeck[0]、gameDeck[1] 等”的每个元素分配给 HTML 中的 div id。我是否需要将元素标识为 = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
解决方案
我理解您的问题的方式是,您希望HTML
使用 card1、card2、card3...card12 等 ID来定位您的 div。
您想img
在每个这些 div 中插入一个标签,该标签src
是 gameDeck 数组的 URI。
下面的代码实现了这一点。我已经测试过了,它工作正常。希望能帮助到你 :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
推荐阅读
- react-native - 反应原生 Azure Iothub 客户端
- javascript - 如何拥有多色折线谷歌地图
- mysql - 如何从db中选择ip?
- angular - 使用 angular-azure-blob-service 时出现 403 错误
- swift - 使用参数以编程方式创建表视图 - swift
- ios - 如何将 GPS 坐标导航到 CameraView
- mongodb - 可以在 mongoDB Shard 集群中进行增量备份吗?没有 opsmanager
- batch-file - 批处理脚本在操作系统和 Winpe 环境中执行时给出不同的输出
- jquery - Material Design Range Slider:可能有 2 个输入/句柄?
- amazon-web-services - 如何监控 aws api 网关上的获取/发布端点?