簡體   English   中英

將 Firebase 中的數據顯示到表格中時出現問題?

[英]Problem displaying data from Firebase into a table?

我正在嘗試將 Firebase 實時數據庫中的數據顯示到我的表中。 我遇到了一個數據格式正確但沒有作為列表的點。 我的結果是這樣的:

在此處輸入圖像描述

我想要完成的是顯示為城市的垂直列表,包括頂部的 state。


    ///Variables including the documents form html
    var head = document.getElementById('tableHead');
    var body = document.getElementById('tableBody');
    var tr = document.createElement('tr');

    ///Access to database 
    var ref = firebase.database().ref('vibes');
    ref.child('state').on('value', gotVibeData);

    function gotVibeData(snapshot) {
        snapshot.forEach(vibeSnapshot => {
            var stateKey = vibeSnapshot.key;    
            Vibes.stateName = stateKey;

            var th = document.createElement('th');
            th.innerText = Vibes.stateName;
            tr.appendChild(th);
            head.appendChild(tr);

            ref.child('state').child(stateKey).child('city').on('value', function(snapshotCity) {
                snapshotCity.forEach(citySnap => {
                    var cityKey = citySnap.key;
                    Vibes.cityName = cityKey;

                    var td = document.createElement('td');
                    td.innerText = cityKey;
                    tr.appendChild(td);
                    body.appendChild

                });
            });
        });
    }

    class Vibes {
        constructor(stateName, cityName) {
            this.stateName = stateName;
            this.cityName = cityName;
        }
    }

</script>

上面的代碼是給出結果的代碼。 我的代碼是在 tbody 內部創建一個 th

在您的代碼中,您只使用了一個tr將所有數據放在一行中:

<tr> <th></th> <td></td> <td></td> </tr>

但你需要的是:

<tr> <th></th> </tr>
<tr> <td></td> </tr>
<tr> <td></td> </tr>

在以下情況下,每次遇到cityKeycity時,請考慮添加一行:

 ///Variables including the documents form html var head = document.getElementById('tableHead'); var body = document.getElementById('tableBody'); function gotVibeData() { /*snapshot.forEach(vibeSnapshot => { var stateKey = vibeSnapshot.key; Vibes.stateName = stateKey;*/ var trHead = document.createElement('tr'); var th = document.createElement('th'); th.innerText = 'CA'; trHead.appendChild(th); head.appendChild(trHead); ['city1', 'city2'].forEach(city => { var tr = document.createElement('tr'); var td = document.createElement('td'); td.innerText = city; tr.appendChild(td); body.appendChild(tr); }); /*}); });*/ } /*class Vibes { constructor(stateName, cityName) { this.stateName = stateName; this.cityName = cityName; } }*/ gotVibeData();
 <table> <thead id="tableHead"> </thead> <tbody id="tableBody"> </tbody> </table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM