来自JS for循环的图像不会加载HTML

时间:2018-04-02 01:28:29

标签: javascript html

我在JS中有一系列图像需要包含在HTML中。这是我的数组和JS代码:

// Data for the "HTML Images" Page

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"}
];

window.onload = function(){
    var figure = "<figure>";
    for(var i = 0; i <= images.length; i++){
        figure += '<img src="'+ images[i].url + '" ' + 'alt="' + images[i].alt + '">' 
        + '<figcaption>' + images[i].caption + "</figcaption>"   
    }figure += "</figure>";

    var myContainer = document.querySelector("#image").innerHTML = figure;
}

这是HTML容器:

<section class="main center">

            <h2>HTML Images</h2>
            <a href="https://ict.senecacollege.ca/" target="_blank">
                <img src="assignment3/img/ict.png">
            </a>
            <h2>Scenes</h2>
            <div id="image"></div>

    </section>

但页面是空白的。我假设问题是我的连接,但我找不到它的错误。

3 个答案:

答案 0 :(得分:3)

数组'images'中有5个项目。你的循环从0开始向上,直到包括5,这是6次迭代。

你想要i < images.length

您当前正在访问undefined的.url(不存在的索引的默认值)

答案 1 :(得分:1)

由于等号,您正在迭代一次,并且导致错误。长度为6的数组的最后一个元素为5。

答案 2 :(得分:1)

您还可以将数组reduce转换为字符串:

const figure = images.reduce(
  (all,image)=>
    all + '<img src="'+ image.url + '" ' + 'alt="' + image.alt + '">' 
    + '<figcaption>' + image.caption + "</figcaption>",
  "<figure>"//initial value
) + "</figure>";