2 回答
TA贡献1799条经验 获得超8个赞
您必须从每个快照中获取密钥,确定它是奇数还是偶数,然后根据该值更新 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贡献1816条经验 获得超4个赞
使用 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>');
});
});
添加回答
举报