You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向JavaScript商品数组中添加图片字段并完成页面渲染

实现步骤

1. 给商品数组添加图片地址字段

你只需给每个商品对象新增imgUrl属性,存储对应商品的图片地址即可,地址可以是公开的网络图片链接,也可以是本地项目里的图片相对路径,修改后的数组示例:

const products = [
    { id: 1, title: "title", description: "description", price: 123, imgUrl: "./images/product1.jpg"},
    { id: 2, title: "title B", description: "description B", price: 456, imgUrl: "./images/product2.jpg"},
    { id: 3, title: "title C", description: "description C", price: 789, imgUrl: "./images/product3.jpg"},
];

如果你的图片和当前HTML文件存放在同一目录,直接写图片文件名即可,比如imgUrl: "product1.jpg"。

2. 修改渲染函数,新增图片渲染逻辑

在displayProducts的拼接HTML部分,插入<img>标签读取对应商品的图片地址即可,这里建议把图片放在标题上方展示,同时给img标签加上alt属性作为图片加载失败时的替代文本:

function displayProducts() {
    let container = document.querySelector(".container");
    // 优化点:先拼接所有HTML再一次性赋值,避免多次重绘页面,性能更好
    let htmlStr = ''
    for (let product of products) {
        htmlStr +=
            `<div class="item">` +
            // 新增的图片标签,你可以给它加class自定义宽高、边距等样式
            `<img src="${product.imgUrl}" alt="${product.title}" class="product-img">` +
            `<h2>${product.title}</h2>` +
            `<p>${product.description}</p>` +
            `<p>Pris: <b>${product.price}</b></p>` +
            `<button onclick="addToCart(${product.id})">Buy</button>` +
            `</div>`; // 补充原代码遗漏的div闭合标签,避免样式错乱
    }
    container.innerHTML = htmlStr
}

可选优化

你可以给图片加CSS样式控制展示效果,举个例子:

.product-img {
  width: 100%;
  height: 200px;
  object-fit: cover; /* 避免图片拉伸变形 */
  border-radius: 4px;
}

内容的提问来源于stack exchange,提问作者user17608953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:45:05