首页 > 解决方案 > 如何检索存储在 Firebase 数据库中的 URL,然后填充图像标签的 src?

问题描述

我遵循了一个关于如何创建 Firebase 数据库的好教程。(https://www.youtube.com/watch?v=kmTECF0JZyQ)然后我设法检索到这些数据以显示在我的网页上。使用文本和数字很清楚,但是当我想在我的 HTML 页面上呈现图像时会发生什么?图片来自我的网站。

因此,我可以使用文本字段来存储图像的 URL,但是在创建标记时如何在我的页面上显示它,但显然不是填充 URL 的“src”。欢迎任何帮助。

const productList = document.querySelector('#productList');

function renderProducts(doc) {
    let li = document.createElement('li');
    let title = document.createElement('span');
    let price = document.createElement('span');
    let image = document.createElement('img');

    li.setAttribute('data-id', doc.id);
    title.textContent = doc.data().title;
    price.textContent = doc.data().price;
    image.textContent = doc.data().image;

    li.appendChild(title);
    li.appendChild(price);
    li.appendChild(image);

    productList.appendChild(li);
}

db.collection('Products').orderBy('title').get().then((snapshot) => {
    snapshot.docs.forEach(doc => {
        renderProducts(doc);
    })
})

标签: javascripthtmlfirebasegoogle-cloud-firestore

解决方案


img元素没有 textContent 属性。我想您打算使用img.src将 URL 加载到img

image.src = doc.data().image;

推荐阅读