【问题标题】:Adding an image to an array将图像添加到数组
【发布时间】:2022-01-12 03:57:29
【问题描述】:

我是 javascript 初学者,这是我在学校的第一个项目。我试图显示带有标题等的图像,但我只是不知道如何将图像添加到我的数组中并显示它们。

const products = [
    { id: 1, title: "title", description: "description", price: 123},
    { id: 2, title: "title B", description: "description B", price: 456 },
    { id: 3, title: "title C", description: "description C", price: 789 },
];

function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML +=
            `<div class="item">` +
            `<h2>${product.title}</h2>` +
            `<p>${product.description}</p>` +
            `<p>Pris: <b>${product.price}</b></p>` +
            `<button onclick="addToCart(${product.id})">Buy</button>`;
    }
}

【问题讨论】:

标签: javascript arrays image


【解决方案1】:

只需添加另一个索引,该索引将图像源/路径作为值,并将其填充到 div 中,就像您为标题/描述所做的那样。对于图像的路径,您可能需要适当地添加相对/绝对路径。

    const products = [
    { id: 1, title: "title", description: "description", price: 123, img: 'images/image1.jpeg'},
    { id: 2, title: "title B", description: "description B", price: 456, img: 'images/image3.jpeg' },
    { id: 3, title: "title C", description: "description C", price: 789, img: 'images/image3.jpeg' },
];

function displayProducts() {
    let container = document.querySelector(".container");

    for (let product of products) {
        container.innerHTML +=
            `<div class="item">` +
            `<h2>${product.title}</h2>` +
            `<p>${product.description}</p>` +
            `<p>Pris: <b>${product.price}</b></p>` +
            `<img src=${product.img} />
            `<button onclick="addToCart(${product.id})">Buy</button>`;
    }
}

【讨论】:

    【解决方案2】:
      function displayProducts() {
        let container = document.querySelector(".container");
    
        for (let product of products) {
            container.innerHTML +=
            `<div class="item">` +
            `<h2>${product.title}</h2>` +
            `<p>${product.description}</p>` +
            `<p>Pris: <b>${product.price}</b></p>` +
            `<p><img src="photoUrl.png" alt="photo" /></p>` +
            `<button onclick="addToCart(${product.id})">Buy</button>`;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多