gpt4 book ai didi

javascript - HTML5 中的图像数组

转载 作者:行者123 更新时间:2023-11-28 04:29:14 25 4
gpt4 key购买 nike

所以如果我想在网上抓取一些图片,将它们放在一个数组中并在我正在制作的网站上使用它们,我该如何使用 Javascript 来完成。

var images = [
{caption: "Red Slate Mountain", alt: "Mountain", url:"https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Red_Slate_Mountain_1.jpg/320px-Red_Slate_Mountain_1.jpg"},

{caption: "St. Petersburg River", alt: "River", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Saint-petersburg-river-march-24-2016.jpg/320px-Saint-petersburg-river-march-24-2016.jpg"},

{caption: "Lybian Desert", alt: "Desert", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Libyan_Desert_-_2006.jpg/320px-Libyan_Desert_-_2006.jpg"},

{caption: "Azerbaijan Forest", alt: "Forest", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Azerbaijan_forest_3.JPG/320px-Azerbaijan_forest_3.JPG"},

{caption: "Indonesian Jungle", alt: "Jungle", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Indonesian_jungle3%2C_Zoo_Prague.jpg/320px-Indonesian_jungle3%2C_Zoo_Prague.jpg"}
];

那些是一些图片,我在图片下方有一个标题,如果它不加载图片,则为 alt,以及位置的 url。

我目前拥有的容器是:

window.onload = function(){
var imageContainer = document.querySelector("#image");

for(var i=0; i < images.length; i++){
var myImageStr += "<img alt='" + images[i].alt + "'" +
" src='" + images[i].url + "' />";

imageContainer.innerHTML = myImageStr;
};

它不加载任何东西,所以我假设我在这里遇到了一些问题,只是不确定是什么。请提供任何帮助:)

最佳答案

我建议您同时使用 createElement()appendChild() 函数,而不是将静态字符串放入 DOM 中。看起来清晰多了。

var images = [{caption:"Red Slate Mountain",alt:"Mountain",url:"https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Red_Slate_Mountain_1.jpg/320px-Red_Slate_Mountain_1.jpg"},{caption:"St. Petersburg River",alt:"River",url:"https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Saint-petersburg-river-march-24-2016.jpg/320px-Saint-petersburg-river-march-24-2016.jpg"},{caption:"Lybian Desert",alt:"Desert",url:"https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Libyan_Desert_-_2006.jpg/320px-Libyan_Desert_-_2006.jpg"},{caption:"Azerbaijan Forest",alt:"Forest",url:"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Azerbaijan_forest_3.JPG/320px-Azerbaijan_forest_3.JPG"},{caption:"Indonesian Jungle",alt:"Jungle",url:"https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Indonesian_jungle3%2C_Zoo_Prague.jpg/320px-Indonesian_jungle3%2C_Zoo_Prague.jpg"}],

parent = document.getElementById('box');
window.onload = function() {
images.forEach(function(v) {
var img = document.createElement("img");
img.src = v.url;
img.alt = v.alt;
box.appendChild(img);
})
}
<div id='box'></div>

关于javascript - HTML5 中的图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com