gpt4 book ai didi

javascript - 为什么 img.src 不在每个 "li"中定义 img-tag 的来源?

转载 作者:行者123 更新时间:2023-12-03 07:10:23 24 4
gpt4 key购买 nike

我想在下面代码中的每个“li”中添加来自 Firebase Storage 的图像,但只有第一个 li 有图像。其他 img 标签上没有定义的 src。控制台没有报错,但是控制台记录了每张图片的picURL,但是不会应用到src

代码:

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();
const li = `
<li>
<div class="title">${post.title}</div>
<div class="content">${post.content}</div>
<img class="img">
</li>
`;

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

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

if (snapshot.docs.length > 0) {
snapshot.docs.forEach(doc => {

const data = doc.data();

const picURL = data.picURL

console.log(picURL)

var img = document.querySelector(".img")

img.src = picURL

})
} else {

console.log("PicURL doesn't exist")

}

})
html += li
})

posts.innerHTML = html;

}
});

最佳答案

问题出在这一行:

var img = document.querySelector(".img")

每次运行时,您都会从 HTML 中加载第一个 .img 元素。您真正想要做的是在您当前构建的 li 上设置图像。

解决此问题的最简单方法是仅将 img 标记添加到循环内的 li 中:

const setupPosts = (data) => {

let html = '';
data.forEach(doc => {

var docRefIDpost = docRef.id

const post = doc.data();
let li = `
<li>
<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) {
snapshot.docs.forEach(doc => {
const data = doc.data();

const picURL = data.picURL

console.log(picURL)

var img = document.querySelector(".img")

li += `<img class="${picURL}">`;
})
} else {
console.log("PicURL doesn't exist")
}

})
li += "</li>";

html += li
})

posts.innerHTML = html;
}
});

更新代码:

const setupPosts = (data) => {
let html = '';
data.forEach(doc => {
var docRefIDpost = docRef.id

const post = doc.data();
let li = `
<li>
<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) {
snapshot.docs.forEach(doc => {
const data = doc.data();
const picURL = data.picURL

var img = document.querySelector(".img")

li += `<img class="${picURL}">`;
})
} else {
console.log("PicURL doesn't exist")
}

li += "</li>";
html += li
posts.innerHTML = html;
})
})
}
});

这会在读取每个文档后更新 HTML。

关于javascript - 为什么 img.src 不在每个 "li"中定义 img-tag 的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64403265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com