如何从每个唯一的 Firestore 文档中检索 1 张图片 URL 并使用该 picURL

我想进入特定集合中的每个文档并检索保存的 picURL,然后将 src 设置为 li 中的 img 标记。我试过一个代码,它部分有效。它设置了 img src,但它是相同的 src。我想检索两个(或更多)不同的 picURL,并将这些作为 img src 设置为两个(或更多)唯一的 img src。我希望这个问题是有道理的,很难解释。我将添加一些图片和代码片段以帮助理解。


Java脚本:


var postDocRef = db.collection('posts').doc(uid).collection('userPosts')


postDocRef.get().then(snapshot => {

setupPosts(snapshot.docs)

})


const posts = document.querySelector('.posts');


const setupPosts = (data) => {

    let html = '';

    data.forEach(doc => {

        var docRefIDpost = docRef.id


        const post = doc.data();

        let li = `

        <li class="post">

            <div class="title">${post.title}</div>

            <div class="content">${post.content}</div>

        `;


        var imgRef = db.collection('posts').doc(uid).collection('userPosts');

        imgRef.get().then(function(snapshot) {

            

            if (snapshot.docs.length > 0) {

                

                let doc = snapshot.docs[0]

                    const data = doc.data();

                    const picURL = data.picURL


                    li += `<img class="img" src="${picURL}">`;         

            }


            li += "</li><br></br>";

            html += li

            posts.innerHTML = html;

        })

    })

}

});


浮云间
浏览 99回答 1
1回答

HUWWW

试试这个解决方案。var postDocRef = db.collection('posts').doc(uid).collection('userPosts')postDocRef.get().then(snapshot => {setupPosts(snapshot.docs)})const posts = document.querySelector('.posts');const setupPosts = (data) => {&nbsp; &nbsp; let html = '';&nbsp; &nbsp; data.forEach(doc => {&nbsp; &nbsp; &nbsp; &nbsp; var docRefIDpost = docRef.id&nbsp; &nbsp; &nbsp; &nbsp; const post = doc.data();&nbsp; &nbsp; &nbsp; &nbsp; let li = `<li class="post">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="title">${post.title}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="content">${post.content}</div>`;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; li += (post.picURL ? `<img class="img" src="${post.picURL}">` : ``);&nbsp; &nbsp; &nbsp; &nbsp; li += `</li><br></br>`;&nbsp; &nbsp; &nbsp; &nbsp; html += li&nbsp; &nbsp; })&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; posts.innerHTML = html;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript