2017-03-20 38 views
0

我一直試圖從Firebase輸出多個值到我的HTML文檔,但是,我可以使用console.log獲取所有子輸出,但是當我嘗試添加它時到HTML中它只輸出1個值。我試圖使用forEach,但我無法讓它工作(不知道我是否犯了一個錯誤)。可以在console.log中獲取多個輸出,但不能輸出HTML

我到目前爲止的代碼是

const dbRefObjectPosts = dbRefObject.child('Posts'); 

    dbRefObjectPosts.on("value", function(snap){ 
     snap.forEach(function(childSnapshot){ 
      document.getElementById('object').innerHTML = (
       "Title: " + childSnapshot.val().Title + "</br>" + 
       "Message: " + childSnapshot.val().Message + "</br>" + 
       "Posted: " + childSnapshot.val().Posted 
      ); 
      console.log(childSnapshot.val().Message); 
     }); 
    }); 

的HTML輸出

Title: 6756775 
Message: 56756575776 
Posted: Date: 19/3/2017 @ 23:2:40 

中的console.log輸出

out with friends 
BLOG.js:61 this is a test 
BLOG.js:61 03:11 am and this is kind of working. 
BLOG.js:61 The time is now 03:59 and things are coming good finally. 
BLOG.js:61 Ok time is 04:42 going to my bed. 
BLOG.js:61 5676576756575 
BLOG.js:61 56756575776 
+0

嘗試'.innerHTML + = ...'當您執行'.innerHTML ='時,將以前的值替換爲新的值。 – Rajesh

+0

@Rajesh謝謝大部分工作,但標題只輸出一次任何想法如何解決這個問題? – Woddell

+0

只需一個指針,在循環中創建'htmlString'並在循環之後設置一次。在循環中操作DOM是一種不好的做法。也嘗試記錄最後的字符串。這可能會幫助你解決題目問題。很難想象它。 – Rajesh

回答

2

這個腳本能夠解決您的問題。

dbRefObjectPosts.on("value", function(snap){ 
     snap.forEach(function(childSnapshot){ 
      document.getElementById('object').innerHTML += (
       "Title: " + childSnapshot.val().Title + "</br>" + 
       "Message: " + childSnapshot.val().Message + "</br>" + 
       "Posted: " + childSnapshot.val().Posted + 
       "<br/><br/>" 
      ); 
      console.log(childSnapshot.val().Message); 
     }); 
    }); 
相關問題