将Firebase中的数据显示到表格中时出现问题?

时间:2019-10-21 07:18:33

标签: javascript html firebase firebase-realtime-database

我正在尝试将Firebase Realtime数据库中的数据显示到我的表中。我发现数据格式正确但没有列表形式。我的结果是这样:

enter image description here

我要完成的工作是显示为垂直的城市列表,包括顶部的州。


    ///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

1 个答案:

答案 0 :(得分:1)

在您的代码中,您仅使用了一个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>