首页 > 解决方案 > 将图像元素数组分配给 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.      
});        

标签: javascriptarraysdom

解决方案


我理解您的问题的方式是,您希望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);
});

推荐阅读