2 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
您必須從每個(gè)快照中獲取密鑰,確定它是奇數(shù)還是偶數(shù),然后根據(jù)該值更新 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);
});

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用 forEach 無(wú)法完成,詳細(xì)代碼如下:
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>');
});
});
添加回答
舉報(bào)