자바 스크립트를 사용하여 검색된 firabase 데이터를 다른보기에 표시하는 방법
Nov 19 2020
홀수 ID의 경우 설명을 표시하고 이미지를 표시하고 짝수 ID의 경우 이미지를 표시하고 설명을 표시합니다. 그러나 내가 사용하는 코드는 다음과 같습니다.
var rootRef = firebase.database().ref().child("products");
rootRef.on("child_added", snap => {
//alert(snap.val());
var desp = snap.child("description").val();
var image = snap.child("image").val();
var image_and_desp_string =
'<div class="row">'
+ '<div class="col-md-6 col-sm-6 productDetails">'
+ '<p>' + desp + '</p>'
+ '</div>'
+ '<div class="col-md-6 col-sm-6">'
+ '<img src="' + image + '">'
+ '</div>'
+ '</div>';
$("#product_section").append(image_and_desp_string);
});
이 코드는 모든 데이터에 대한 이미지와 설명을 나란히 표시합니다. 홀수 ID와 짝수 ID 데이터에 차이를 만들고 싶습니다. 도와주세요!! 내 firebase 데이터베이스는이 이미지와 같습니다.

답변
1 FrankvanPuffelen Nov 19 2020 at 14:28
각 스냅 샷에서 키를 가져 와서 홀수인지 짝수인지 확인한 다음이를 기반으로 HTML을 업데이트해야합니다.
var rootRef = firebase.database().ref().child("products");
rootRef.on("child_added", snap => {
var key = snap.key;
var isOdd = parseInt(snap.key) % 2 == 1;
var desp = snap.child("description").val();
var image = snap.child("image").val();
var imageString = '<div class="col-md-6 col-sm-6">'
+ '<img src="' + image + '">'
+ '</div>';
var despString = '<div class="col-md-6 col-sm-6 productDetails">'
+ '<p>' + desp + '</p>'
+ '</div>';
var image_and_desp_string =
'<div class="row">'
+ (isOdd ? despString : imageString)
+ (isOdd ? imageString : despString)
+ '</div>';
$("#product_section").append(image_and_desp_string);
});
Ferdousi Nov 19 2020 at 14:50
forEach를 사용하여 수행 할 수 없으며 세부 정보 코드는 다음과 같습니다.
var query = firebase.database().ref("products").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
const key = Number(childSnapshot.key);
console.log(key);
// childData will be the actual contents of the child
var desp = childSnapshot.child("description").val();
var img = childSnapshot.child("image").val();
key % 2 === 0 ?
$("#product_section").append( //show value from Firebase, image then description '<div class="row">' + '<div class="col-md-6 col-sm-6">' + '<img src="' + img + '">' + '</div>' + '<div class="col-md-6 col-sm-6 productDetails">' + '<p>' + desp + '</p>' + '</div>' + '</div>') : $("#product_section").append( //show value from Firebase
'<div class="row">'
+ '<div class="col-md-6 col-sm-6 productDetails">'
+ '<p>' + desp + '</p>'
+ '</div>'
+ '<div class="col-md-6 col-sm-6">'
+ '<img src="' + img + '">'
+ '</div>'
+ '</div>');
});
});