2 回答

TA貢獻1807條經驗 獲得超9個贊
因此,考慮到您想要獲得比實際告訴數據庫更多的數據,答案會更加復雜。每個文檔的數據結構可能更像這樣:
{
? url: /* string containing image's url */,
? rating: [4, 2, 5, 0] /* array containing ratings given for this image
}
每個圖像應該以大致相同的方式表示 - 所以如果你有一個名為 的集合images,那么你可能會有這樣的東西:
const dbRef = firebase.firestore();
const imagesRef = dbRef.collection('images');
const oneImage = imagesRef.doc('JdBPHMYWfNMMlMpfsjv5');
oneImage.get().then(function(doc){
? console.log( doc.data() )
? // that might return?
? {
? ? 'url': '/img/sun002.jpg',
? ? 'rating': [5,2,3,2,0,5]
? }
? /***
? ?* but! In your case, you'd likely want to create the HTML fragment
? ?* you'll be injecting for this particular image:
? ?***/
? // so let's pull all the stuff out of the database, and create an object
? //? that includes the image's id.
? const image = {id: doc.id, ...doc.data() }
? // Using that, we can create an HTML fragment that generates the radio buttons
? const imageEl = document.createRange().createContextualFragment(`<div class='img-container'>
? <img src='${image.url}'>
? <fieldset class='image-rating'>Rate this image:?
? ? <label>0 <input type='radio' name='rating' data-uid='${image.id}' value=0 /></label>
? ? <label>1 <input type='radio' name='rating' data-uid='${image.id}' value=1 /></label>
? ? <label>2 <input type='radio' name='rating' data-uid='${image.id}' value=2 /></label>
? ? <label>3 <input type='radio' name='rating' data-uid='${image.id}' value=3 /></label>
? ? <label>4 <input type='radio' name='rating' data-uid='${image.id}' value=4 /></label>
? ? <label>5 <input type='radio' name='rating' data-uid='${image.id}' value=5 /></label>
? </fieldset>
</div>
'`)
// Let's add a listener for the click on the wrapper for all these radios
imageEl.querySelector('.image-rating').addEventListener('click', handleRatingClick)
// And finally, let's add this image block to the page!
document.querySelector("#images-content-pane").appendChild(imageEl)
})
doc
請注意,每個圖像在集合中都是其自己的,但它可以包含您可能喜歡的任何屬性。您可以添加一個caption
屬性,或者任何可能對您有用的內容。
但有幾點需要注意:
我以編程方式創建每個圖像的容器,并將偵聽器動態添加到每個圖像的字段集。
我正在
data-uid
向每個單選按鈕添加一個屬性。我們稍后需要它,以便我們知道要更新哪個圖像文檔!
然后,稍后,當您為此圖像添加評級時,您只需引用該特定圖像并將所選評級添加到數組中即可:
// In my case, I had a fieldset wrap all my radio buttons, and a click was handled there:
const handleRatingClick = (event) =>{
? // First, let's get the clicked el:
? const ratingBtn = event.target;
? const imageId = ratingBtn.dataset.uid;
? const rating = ratingBtn.value;
? // And here I update the array in the rating property, by adding the given value
? imagesRef.doc(imageId).update({
? ? rating: firebase.firestore.FieldValue.arrayUnion(Number(rating))
? })
}
請注意,這不是唯一的方法,甚至不是正確的方法。重點是,您需要將每個圖像視為數據庫中的文檔,并且需要在創建或更新它時為 firestore 提供一個對象。
您可以像您正在做的那樣,并使用 localStorage/sessionStorage 中的圖像,但即便如此, sessionStorage 中的值也需要是一個對象,包含
{
? url,
? answer
}
這樣做.set()只會覆蓋每次答案的值,而不是隨著時間的推移存儲它們。另外,為了讓你的工作正常,你需要在某個地方存儲一個 doc.id 。
添加回答
舉報