如何获取存储在Firebase数据库中的URL,然后填充图像标签的src?

时间:2020-04-12 16:00:34

标签: javascript html firebase google-cloud-firestore

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

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

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);
    })
})

2 个答案:

答案 0 :(得分:1)

img元素没有textContent属性。我想您打算使用img.src将此网址加载到img中:

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

答案 1 :(得分:0)

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.src = doc.data().image;

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

    productList.appendChild(li);
}

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