我想使用 Firebase Storage 通過 javascript 在我的網頁上顯示多張圖片。我用:
getDownloadURL(ref(storage, imageIndexPathRoot)).then((url) =>{
img.setAttribute('src', url);
問題是只顯示最后一個影像。例如,如果我的檔案夾中有 5 張圖片,則對所有 5 張影像正確執行帶有 imageIndexPathRoot 的 getDownload 行,但僅在最后一張影像中執行 img.setAttribute... 行,并且僅在網頁上顯示此影像。
// Now we get the references of these images
listAll(listRef).then((res) => {
res.items.forEach(function(imageRef) {
// And finally display them
console.log(imageRef);
displayImage(imageRef);
});
}).catch((error) => {
// Handle any errors
console.log("Error 1");
});
function displayImage(imageRef) {
const img = document.getElementById('tierFoto');
img.src = imageRef.fullPath;
getDownloadURL(ref(storage, imageIndexPathRoot)).then((url) =>{
img.setAttribute('src', url);
})
.catch((error) => {
console.log(error);
});
}
}
uj5u.com熱心網友回復:
每次displayImage被呼叫時,它都會:
const img = document.getElementById('tierFoto')
因此它將每個影像設定為相同的 HTML 元素,這解釋了為什么您只能看到最后一個影像。
如果您想在每次呼叫 時顯示單獨的影像,則每次displayImage都需要獲取(或傳入)不同的 HTML 元素。如何做到這一點,取決于您的 HTML 結構。
例如,如果您的 HTML 包含img帶有編號 ID 的元素,您可以執行以下操作:
res.items.forEach(function(imageRef, i) { // ?? get index from forEacj
displayImage(imageRef, i); // ?? pass it to displayImage
});
進而
function displayImage(imageRef, index) { // get index from caller
const img = document.getElementById('tierFoto-' index); // use index to look up element
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369209.html
標籤:javascript html 火力基地 网址 火力存储
上一篇:Firebase-如何擴展FirebaseError?
下一篇:捆綁關聯的Firebase源后,是否應該從html<script>標記中洗掉“type="module"”宣告?
