使用 for 循环显示 HTML 使用 JavaScript 的元素

Using a for loop to display HTML element using JavaScript

我目前正在做一个项目,我有一个画廊 (Gallery.php),其中包含图像轮播,如果单击图像,图像 ID(我已设置)和图像 URL 被添加到 localStorage 中的二维数组中。我正在尝试从主页 (index.php) 中的 localStorage 检索数组,该数组通过登录到控制台进行确认,但是我正在努力寻找一种循环遍历数组并显示 bootstrap 的方法卡头是 ImageID,正文是带 URL 的图像。我意识到这在 PHP 中会更容易,但项目简报要求在 JavaScript 中明确完成此操作。 这是我想要实现的伪代码

FOR image IN ImageArray
   CREATE card
   SET card.header TO image.ImageID
   SET card.body TO img element SRC = ImageURL
   END CARD
ENDFOR

这是设置ImageID和URL然后推送到localStorage数组的函数

function SetClickedPhotoURL(URL, ImageID) {
    //Check if item is already set
    for (let x = 0; x<images.length; x++) {
        if (images[x][0] == ImageID) {
            console.log("Image already added");
            //Cancel function
            return;
        }
    }
    images.push([ImageID, URL]);
    window.localStorage.setItem("images", JSON.stringify(images));
}

我正在尝试在 PHP 中使用 foreach 循环实现类似的效果,如果有解决方案,我也在这个项目中使用 JQuery。

此解决方案的 PHP 将与此类似,如果它能帮助您理解我想要实现的目标的话。

<?php
foreach ($ImageArray as $Image) {
   ?>
   <div class="col-md-4 col-12 mb-3">
       <div class="card border">
           <div class="card-header text-center">
               <h5><?php echo $Image[0];?></h5> <!--$Image[0] is the ImageID-->
           </div>
           <div class="card-body text-center">
              <img src=<?php echo $Image[1];?> class="img-fluid" alt=<?php echo $ImageID;?>/>
              <!--$Image[1] is where the URL is stored-->
           </div>
       </div>
    </div>
    <?php
}
?>

如有任何帮助,我们将不胜感激!

遍历图像,并为每个元素创建一张卡片并将其附加到目的地(假设为 #target):

images.forEach(function(image) {
   $('#target').append(
   `<div class="col-md-4 col-12 mb-3">
       <div class="card border">
           <div class="card-header text-center">
               <h5>${image[0]}</h5>
           </div>
           <div class="card-body text-center">
              <img src="${image[1]}" class="img-fluid" alt="${image[0]}"/>
           </div>
       </div>
    </div>
    `
    );
});